diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..6fb5f5e10e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,69 @@ +name: Bug report +description: Report a bug with the twilio-python helper library. +title: "[BUG] Describe the issue briefly" +labels: "type: bug" +body: + - type: markdown + attributes: + value: | + Thank you for reporting a bug in the twilio-python helper library. Please provide the details below to help us investigate and resolve the issue. + + - type: textarea + attributes: + label: Describe the bug + description: Provide a clear and concise description of the issue. + placeholder: A clear and concise description of the bug. + validations: + required: true + + - type: textarea + attributes: + label: Code snippet + description: Provide the code snippet that reproduces the issue. + placeholder: "```\n// Code snippet here\n```" + validations: + required: true + + - type: textarea + attributes: + label: Actual behavior + description: Describe what actually happened. + placeholder: A description of the actual behavior. + validations: + required: true + + - type: textarea + attributes: + label: Expected behavior + description: Describe what you expected to happen. + placeholder: A description of the expected outcome. + validations: + required: true + + - type: input + attributes: + label: twilio-python version + description: Specify the version of the twilio-python helper library you are using. + placeholder: e.g., 9.4.1 + validations: + required: true + + - type: input + attributes: + label: Python version + description: Specify the version of Python you are using. + placeholder: e.g., 3.9.1 + validations: + required: true + + - type: textarea + attributes: + label: Logs or error messages + description: Provide relevant logs or error messages (if any). + placeholder: "Error: Something went wrong..." + + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + placeholder: Any additional diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..0c022c8ffd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,135 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: + inputs: + python-version: + description: "Python version to test with (or 'all' for full matrix)" + required: false + default: "all" + schedule: + - cron: '30 3 * * 1' # Monday 9AM IST + +env: + ARTIFACTORY_URL: ${{ vars.ARTIFACTORY_URL }} + +jobs: + lockfile-hygiene: + runs-on: ubuntu-x64 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: twilio/sdk-actions/uv-lockfile-hygiene@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + clean-room: 'false' + + test: + name: Test - Python ${{ matrix.python-version }} + needs: [lockfile-hygiene] + runs-on: ubuntu-x64 + if: github.repository_owner == 'twilio' + # make docs takes ~15mins + timeout-minutes: 30 + permissions: + contents: read + id-token: write + strategy: + fail-fast: false + matrix: + python-version: ${{ (github.event_name == 'schedule' || github.event.inputs.python-version == 'all') && fromJson('["3.8","3.9","3.10","3.11","3.12","3.13"]') || fromJson(format('["{0}"]', github.event.inputs.python-version || '3.12')) }} + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + fetch-depth: 0 + + - name: Artifactory OIDC Auth + uses: twilio/sdk-actions/artifactory-oidc@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + ecosystem: python + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + pip install virtualenv --upgrade + make install test-install + make prettier + + - name: Run tests + run: make test-with-coverage + + - name: Run cluster tests + if: ${{ !github.event.pull_request.head.repo.fork }} + env: + TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }} + TWILIO_API_KEY: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY }} + TWILIO_API_SECRET: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY_SECRET }} + TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }} + TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }} + TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }} + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} + run: make cluster-test + + # - name: Verify docs generation + # run: make docs + + deploy-dry-run: + name: Release Readiness Check - Build artifact + needs: [test] + runs-on: ubuntu-x64 + if: github.repository_owner == 'twilio' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + + - name: Artifactory OIDC Auth + uses: twilio/sdk-actions/artifactory-oidc@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + ecosystem: python + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.12" + + - name: Install setuptools + run: pip install setuptools + + - name: Validate version format + run: | + PKG_VERSION=$(python setup.py --version) + echo "Package version: $PKG_VERSION" + echo "PKG_VERSION=$PKG_VERSION" >> "$GITHUB_ENV" + if [[ ! "$PKG_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]]; then + echo "::error::setup.py version must follow semver (got '$PKG_VERSION')" + exit 1 + fi + + - name: Build package + run: | + pip install build + python -m build + + - name: Verify package + run: | + pip install twine + twine check dist/* + + - name: List built artifacts + run: | + echo "Built artifacts:" + ls -lh dist/ + echo "" + echo "Package version: $PKG_VERSION" + + - name: Dry run summary + run: | + echo "--- DRY RUN COMPLETE ---" + echo "All pre-release steps passed for version $PKG_VERSION" + diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000000..0226eeaf29 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,120 @@ +name: Twilio Public release-pypi + +on: + push: + tags: + - '*' + +env: + ARTIFACTORY_URL: ${{ vars.ARTIFACTORY_URL }} + +jobs: + lockfile-hygiene: + runs-on: ubuntu-x64 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: twilio/sdk-actions/uv-lockfile-hygiene@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + clean-room: 'false' + + test: + name: Test - Python ${{ matrix.python-version }} + needs: [lockfile-hygiene] + runs-on: ubuntu-x64 + if: github.repository_owner == 'twilio' + timeout-minutes: 20 + permissions: + contents: read + id-token: write + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + fetch-depth: 0 + + - name: Artifactory OIDC Auth + uses: twilio/sdk-actions/artifactory-oidc@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + ecosystem: python + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + pip install virtualenv --upgrade + make install test-install + make prettier + + - name: Run tests + run: make test-with-coverage + + deploy: + name: Publish to PyPI + needs: [test] + runs-on: ubuntu-x64 + if: success() && github.ref_type == 'tag' && github.repository_owner == 'twilio' + environment: production + permissions: + contents: write # required for creating GitHub Release + id-token: write + attestations: write + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + + - name: Artifactory OIDC Auth + uses: twilio/sdk-actions/artifactory-oidc@23b656b843d2a3461cf38e4fd466c07a822d5fc0 # v1 + with: + ecosystem: python + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.12" + + - name: Install setuptools + run: pip install setuptools + + - name: Validate tag format and version match + run: | + TAG="${GITHUB_REF#refs/tags/}" + if [[ ! "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]]; then + echo "::error::Release tag must be in the form 1.2.3 (got '$TAG')" + exit 1 + fi + VERSION="${TAG#}" + PKG_VERSION=$(python setup.py --version) + echo "Package version: $PKG_VERSION" + echo "PKG_VERSION=$PKG_VERSION" >> "$GITHUB_ENV" + if [ "$VERSION" != "$PKG_VERSION" ]; then + echo "::error::Tag $TAG does not match setup.py version $PKG_VERSION" + exit 1 + fi + + - name: Get tagged version + run: echo "GITHUB_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + + - name: Create GitHub Release + uses: sendgrid/dx-automator/actions/release@08b601b726671445abc798ed59881766ec8fefc6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Build package + run: | + pip install build + python -m build + + - name: Verify package + run: | + pip install twine + twine check dist/* + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1 + + - name: Summary + run: | + echo "Published version $PKG_VERSION to PyPI" diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 1e1c04d500..f5bd133256 100644 --- a/.github/workflows/test-and-deploy.yml +++ b/.github/workflows/test-and-deploy.yml @@ -17,7 +17,7 @@ jobs: timeout-minutes: 20 strategy: matrix: - python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12' ] + python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12', '3.13' ] steps: - name: Checkout twilio-python uses: actions/checkout@v3 @@ -47,6 +47,7 @@ jobs: TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }} TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }} TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }} + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} run: make cluster-test - name: Verify docs generation diff --git a/CHANGES.md b/CHANGES.md index 7c0335ea99..60487c62da 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,992 @@ twilio-python Changelog Here you can see the full list of changes between each twilio-python release. +[2026-08-11] Version 9.11.0 +--------------------------- +**Library - Fix** +- [PR #929](https://github.com/twilio/twilio-python/pull/929): mock HTTP session in TestUserAgentClients to avoid live network calls. Thanks to [@shrutiburman](https://github.com/shrutiburman)! + +**Twiml** +- Remove `` noun from `` verb as part of the AI Assistants deprecation **(breaking change)** +- Add `passports` attribute to `` verb for SHAKEN/STIR passport passthrough + +**Accounts** +- Add `SuppressEmailNotification` parameter to the Secondary Auth Token and Auth Token promotion endpoints. Set it to `true` to suppress the email notification sent to account owners and administrators. Defaults to `false`, preserving existing behavior. +- Add SMS Pumping Protection GET and POST API + +**Ai** +- Removing ai workbench apis + +**Api** +- Add missing `uri` property to the `twiml_session` resource + +**Data-ingress** +- ## 2026-08-07 +- **Removed 1 API path**: +- `/v1/DataQuery` (Realtime DataQuery) +- ## 2026-07-07 +- **Added 1 new API path (data plane)**: +- `/v1/DataQuery` (Realtime DataQuery) +- ## 2026-06-17 +- **Content updates**: +- Added properties to `OAuthJWTBearerCredentials`: privateKey, privateKeyPassphrase +- ## 2026-06-12 +- **Added 16 new path(s)**: +- `/v1/DataSyncs/{syncId}` (FetchDataSync) +- `/v1/CloudAppSources/{sourceId}/Objects` (ListCloudAppObjects) +- `/v1/WarehouseSources/{sourceId}/Preview` (CreateWarehousePreview) +- `/v1/WarehouseSources/{sourceId}/Preview/{operationId}` (FetchWarehousePreview) +- `/v1/DataSample/{operationId}` (FetchDataSample) +- `/v1/ControlPlane/CloudAppSources/{sourceId}` (FetchCloudAppSource, PatchCloudAppSource, DeleteCloudAppSource) +- `/v1/ControlPlane/CloudAppSources/{sourceId}/Datasets` (ListCloudAppDatasets, CreateCloudAppDataset) +- `/v1/ControlPlane/CloudAppSources/{sourceId}/Datasets/{datasetId}` (FetchCloudAppDataset, PatchCloudAppDataset, DeleteCloudAppDataset) +- `/v1/ControlPlane/WarehouseSources/{sourceId}` (FetchWarehouseSource, PatchWarehouseSource, DeleteWarehouseSource) +- `/v1/ControlPlane/WarehouseSources/{sourceId}/Datasets` (ListWarehouseDatasets, CreateWarehouseDataset) +- ...and 6 more paths +- **Removed 16 path(s)**: +- `/v1/DataSyncs/{SyncId}` (FetchDataSync) +- `/v1/CloudAppSources/{SourceId}/Objects` (ListCloudAppObjects) +- `/v1/WarehouseSources/{SourceId}/Preview` (CreateWarehousePreview) +- `/v1/WarehouseSources/{SourceId}/Preview/{OperationId}` (FetchWarehousePreview) +- `/v1/DataSample/{OperationId}` (FetchDataSample) +- `/v1/ControlPlane/CloudAppSources/{SourceId}` (FetchCloudAppSource, PatchCloudAppSource, DeleteCloudAppSource) +- `/v1/ControlPlane/CloudAppSources/{SourceId}/Datasets` (ListCloudAppDatasets, CreateCloudAppDataset) +- `/v1/ControlPlane/CloudAppSources/{SourceId}/Datasets/{DatasetId}` (FetchCloudAppDataset, PatchCloudAppDataset, DeleteCloudAppDataset) +- `/v1/ControlPlane/WarehouseSources/{SourceId}` (FetchWarehouseSource, PatchWarehouseSource, DeleteWarehouseSource) +- `/v1/ControlPlane/WarehouseSources/{SourceId}/Datasets` (ListWarehouseDatasets, CreateWarehouseDataset) +- ...and 6 more paths +- ## 2026-06-11 +- **Added 3 new Signal API path(s) for public exposure (data plane)**: +- `/v1/EventSources/{sourceId}/Signals` (ListSignals) +- `/v1/EventSources/{sourceId}/Signals/{signalKey}` (GetSignalBySignalKey) +- `/v1/EventSources/{sourceId}/SignalStats` (ListSignalStats) +- **Added new Signal API schemas**: +- Signal, SignalListResponse, HourlyStats, SignalStatsResponse +- ## 2026-05-26 +- **Added 12 new path(s) for public exposure**: +- `/v1/ControlPlane/EventSources` (CreateEventSource, ListEventSources) +- `/v1/ControlPlane/EventSources/{SourceId}` (FetchEventSource, PatchEventSource, DeleteEventSource) +- `/v1/ControlPlane/EventSources/{SourceId}/WriteKeys` (CreateWriteKey, ListWriteKeys) +- `/v1/ControlPlane/EventSources/{SourceId}/WriteKeys/{WriteKey}` (DeleteWriteKey) +- `/v1/ControlPlane/EventSources/{SourceId}/Datasets` (CreateEventSourceDataset, ListEventSourceDatasets) +- `/v1/ControlPlane/EventSources/{SourceId}/Datasets/{DatasetId}` (FetchEventSourceDataset, PatchEventSourceDataset, DeleteEventSourceDataset) +- `/v1/ControlPlane/EventSources/{SourceId}/EventSchemas` (CreateEventSchema, ListEventSchemas) +- `/v1/ControlPlane/EventSources/{SourceId}/EventSchemas/{SchemaId}` (FetchEventSchema, PatchEventSchema, DeleteEventSchema) +- `/v1/ControlPlane/AutoInstrumentationRule` (CreateAutoInstrumentationRule, ListAutoInstrumentationRules) +- `/v1/ControlPlane/AutoInstrumentationRule/{AutoInstrumentationRuleId}` (FetchAutoInstrumentationRule, PatchAutoInstrumentationRule, DeleteAutoInstrumentationRule) +- `/v1/ControlPlane/AutoInstrumentationRule/{AutoInstrumentationRuleId}/Versions` (ListAutoInstrumentationRuleVersions) +- `/v1/ControlPlane/AutoInstrumentationRule/{AutoInstrumentationRuleId}/Versions/{Version}` (FetchAutoInstrumentationRuleVersion) +- **Added new schemas**: +- EventSource, EventSourceCreate, EventSourceUpdate +- WriteKey, WriteKeyCreate +- EventSourceDataset, EventSourceDatasetCreate, EventSourceDatasetUpdate +- EventSchema, EventSchemaCreate, EventSchemaUpdate, EventSchemaField, EventSchemaProperty +- AutoInstrumentationRule, AutoInstrumentationRuleCreate, AutoInstrumentationRuleUpdate +- AutoInstrumentationRuleVersion, AutoInstrumentationRuleVersionsResponse +- ## 2026-06-12 +- **Added 16 new path(s)**: +- `/v1/DataSyncs/{syncId}` (FetchDataSync) +- `/v1/CloudAppSources/{sourceId}/Objects` (ListCloudAppObjects) +- `/v1/WarehouseSources/{sourceId}/Preview` (CreateWarehousePreview) +- `/v1/WarehouseSources/{sourceId}/Preview/{operationId}` (FetchWarehousePreview) +- `/v1/DataSample/{operationId}` (FetchDataSample) +- `/v1/ControlPlane/CloudAppSources/{sourceId}` (FetchCloudAppSource, PatchCloudAppSource, DeleteCloudAppSource) +- `/v1/ControlPlane/CloudAppSources/{sourceId}/Datasets` (ListCloudAppDatasets, CreateCloudAppDataset) +- `/v1/ControlPlane/CloudAppSources/{sourceId}/Datasets/{datasetId}` (FetchCloudAppDataset, PatchCloudAppDataset, DeleteCloudAppDataset) +- `/v1/ControlPlane/WarehouseSources/{sourceId}` (FetchWarehouseSource, PatchWarehouseSource, DeleteWarehouseSource) +- `/v1/ControlPlane/WarehouseSources/{sourceId}/Datasets` (ListWarehouseDatasets, CreateWarehouseDataset) +- ...and 6 more paths +- **Removed 16 path(s)**: +- `/v1/DataSyncs/{SyncId}` (FetchDataSync) +- `/v1/CloudAppSources/{SourceId}/Objects` (ListCloudAppObjects) +- `/v1/WarehouseSources/{SourceId}/Preview` (CreateWarehousePreview) +- `/v1/WarehouseSources/{SourceId}/Preview/{OperationId}` (FetchWarehousePreview) +- `/v1/DataSample/{OperationId}` (FetchDataSample) +- `/v1/ControlPlane/CloudAppSources/{SourceId}` (FetchCloudAppSource, PatchCloudAppSource, DeleteCloudAppSource) +- `/v1/ControlPlane/CloudAppSources/{SourceId}/Datasets` (ListCloudAppDatasets, CreateCloudAppDataset) +- `/v1/ControlPlane/CloudAppSources/{SourceId}/Datasets/{DatasetId}` (FetchCloudAppDataset, PatchCloudAppDataset, DeleteCloudAppDataset) +- `/v1/ControlPlane/WarehouseSources/{SourceId}` (FetchWarehouseSource, PatchWarehouseSource, DeleteWarehouseSource) +- `/v1/ControlPlane/WarehouseSources/{SourceId}/Datasets` (ListWarehouseDatasets, CreateWarehouseDataset) +- ...and 6 more paths + +**Deletions** +- # API Changes +- ## 2026-06-23 +- Initial public Rest Proxy registration for the User Data Deletions API +- (`POST` / `GET /v1/UserDataDeletions`, `GET /v1/UserDataDeletions/{deletionId}`, +- `GET /v1/Operations/{operationId}`). +- A single request may mix identifier formats: E.164 phone numbers, email +- addresses, and profile IDs. + +**Destinations** +- # API Changes +- ## 2026-08-07 +- **Content updates**: +- Updated summary for `ListDestinationSupportedEventTypes` +- ## 2026-08-07 +- **Content updates**: +- Updated summary for `ListDestinationSupportedEventTypes` +- ## 2026-08-07 +- **Added 3 new path(s)**: +- `/v1/Catalog/DestinationSupportedEventTypes` (ListDestinationSupportedEventTypes) +- `/v1/ControlPlane/Subscriptions/{subscriptionId}/EventTypes` (ListSubscribedEvents, CreateSubscribedEvent) +- `/v1/ControlPlane/Subscriptions/{subscriptionId}/EventTypes/{eventType}` (GetSubscribedEvent, UpdateSubscribedEvent, DeleteSubscribedEvent) +- **Removed 3 path(s)**: +- `/v1/ControlPlane/Subscriptions/{subscriptionId}/SubscribedEvents` (ListSubscribedEvents, CreateSubscribedEvent) +- `/v1/ControlPlane/Subscriptions/{subscriptionId}/SubscribedEvents/{eventType}` (GetSubscribedEvent, UpdateSubscribedEvent, DeleteSubscribedEvent) +- `/v1/Catalog/DestinationEventTypes` (ListDestinationEventTypes) +- ## 2026-08-04 +- Minor updates (formatting, metadata) +- ## 2026-08-04 +- Minor updates (formatting, metadata) +- ## 2026-08-04 +- Minor updates (formatting, metadata) +- ## 2026-08-04 +- Minor updates (formatting, metadata) +- ## 2026-08-04 +- **Content updates**: +- Added properties to `SubscriptionResponse`: eventTypes +- ## 2026-08-03 +- **Content updates**: +- Added properties to `DestinationType`: documentationUrl, maturity, tier, categories +- ## 2026-07-27 +- Minor updates (formatting, metadata) +- ## 2026-07-23 +- **Content updates**: +- `meta` is now a required property in the response of `ListDestinations`, `ListSubscriptions`, and `ListSubscribedEvents` +- `CreateSubscribedEvent` request body schema consolidated onto `SubscribedEventInput` (previously `SubscribedEventCreate`, a duplicate schema) +- Added response examples for `ListDestinations`, `ListSubscriptions`, and `ListSubscribedEvents` +- ## 2026-07-23 +- **Added 1 new path(s)**: +- `/v1/Catalog/DestinationEventTypes` (ListDestinationEventTypes) +- ## 2026-07-22 +- **Content updates**: +- Added parameter(s) to `ListDestinations`: namePrefix +- Updated description for `UpdateSubscription` +- Added properties to `SubscriptionUpdate`: eventTypes +- ## 2026-07-16 +- Initial release with 9 paths and 18 operations + +**Events** +- Add `stage-ie1` realm support for EventTypes and Schemas endpoints (datataps-catalog) + +**Memory** +- ## 2026-08-10 +- Removed `Events` endpoints from the spec, as they were hidden, never implemented, and are not part of the public API +- ## 2026-08-07 +- **New functionality**: +- Added `pageSize`, `pageToken`, and `orderBy` query parameters to `ListProfileImportsV2`, plus a `meta` object in its response, to support pagination. +- **Content updates**: +- Updated the `ListProfileImportsV2` description to document the new pagination behavior. +- Corrected the example presigned upload URL on `CreateProfilesImportV2` to match the real S3 bucket naming convention. +- Corrected the `meta.key` example on `ListProfileTraits`'s response (was `profiles`, now `traits`) to accurately describe which response field it points to. +- ## 2026-08-07 +- **Content updates**: +- Updated `matchingRules` description in `IdentityResolutionSettingsCore` to remove compound `AND` rule documentation +- ## 2026-07-30 +- **Content updates**: +- Increased the maximum value for the Twilio error `code` from `99999` to `999999` +- ## 2026-07-28 +- **Content updates**: +- Updated the `pageSize` description on the pagination `Meta` schema to clarify it reflects the number of items actually returned, not the requested or default page size. +- ## 2026-07-13 +- **Content updates**: +- Renamed `ListProfiles` response schema references from `ProfileID`/`ProfilesMeta` to `IdentityProfileID`/`IdentityProfilesMeta` (new `IdentityProfilesMeta` schema added; `ProfileID`/`ProfilesMeta` retained for other operations). +- ## 2026-07-08 +- **Content updates**: +- Updated description for `CreateDataMappingSuggestion` +- Updated description for `FetchDataMappingSuggestion` +- ## 2026-07-06 +- **Added 2 new path(s)**: +- `/v1/ControlPlane/Stores/{storeId}/DataMappings/Suggestions` (ListDataMappingSuggestions, CreateDataMappingSuggestion) +- `/v1/ControlPlane/Stores/{storeId}/DataMappings/Suggestions/{suggestionId}` (FetchDataMappingSuggestion) +- ## 2026-06-26 +- **Content updates**: +- Minor updates (formatting, metadata) +- Updated x-twilio location parameter from `instance` to `list` for all endpoints that don't end with a /{param} +- Updated description for `UpdateProfileTraits` +- Updated summary for `UpdateProfileTraits` +- Removed properties from `MappingTraitItem`: fieldName +- Removed `additionalProperties` from `allof` schemas since it isn't supported and causes invalid lint errors on example blocks. +- matruity ga and libraryVisibility public +- ## 2026-06-24 +- **Content updates**: +- Add ConversationID as an optional query parameter for ListObservations and ListConversationSummaries +- ## 2026-05-01 +- **Content updates**: +- Updated description & summary for `UpdateProfileTraits` +- Updated description for `FetchIdentityResolutionSettings` +- Removed properties from `MappingTraitItem`: fieldName +- Updated patch Observations to not require `occurredAt`, `content`, or `source` +- ## 2026-04-28 +- **Content updates**: +- Updated description for `UpdateProfileTraits` +- Updated summary for `UpdateProfileTraits` +- Added properties to `TraitDefinition`: validationRule +- Removed properties from `MappingTraitItem`: fieldName + +**Messaging_admin** +- Add Intelligent Alerts endpoints at `/v1/Messaging/IntelligentAlertsEvents/*`, routing to intelligent-alerts-api via messaging-monkey-backend. Account SID is a required query parameter (`accountSid`) on all three endpoints. + + +[2026-05-07] Version 9.10.9 +--------------------------- +**Conversations** +- update actions api visibility + +**Memory** +- ## 2026-05-07 +- **Content updates**: +- include store api + + +[2026-05-07] Version 9.10.7 +--------------------------- +**Library - Chore** +- [PR #922](https://github.com/twilio/twilio-python/pull/922): add init for knowledge. Thanks to [@kridai](https://github.com/kridai)! + +[2026-05-06] Version 9.10.6 +--------------------------- +**Library - Chore** +- [PR #921](https://github.com/twilio/twilio-python/pull/921): new api updates. Thanks to [@kridai](https://github.com/kridai)! + +**Twiml** +- Set `recording_configuration_id` attribute to public visibility in ``, ``, `` verbs and `` noun + +**Api** +- Add RecordingConfigurationId parameter for CreateCall, CreateCallRecording, CreateConferenceRecording, and CreateParticipant endpoints + +**Authy** +- # Changelog +- ## v1 +- Added Authy API v1 under `/v1` — initial onboarding of Public API (`/v1/protected/*`), Device API (`/v1/json/*`), and Dashboard API (`/v1/dashboard/*`) behind REST Proxy using transparent proxy mode. + +**Data-ingress** +- ## 2026-04-21 +- **Content updates**: +- Updated description for `CreateDataSync` +- Updated description for `DeleteCloudAppDataset` +- Updated description for `DeleteWarehouseDataset` +- ## 2026-04-20 +- Minor updates (formatting, metadata) +- ## 2026-04-17 +- updated operationId for dataplane APIs,Minor updates (formatting, metadata) +- ## 2026-04-15 +- libraryVisibility to private +- ## 2026-04-14 +- **Added 1 new path(s)**: +- `/v1/DataSyncs/Latest` (GetLatestDataSyncs) + +**Memory** +- ## 2026-04-21 +- **Content updates**: +- Remove Prefer/Async-Operation headers +- ## 2026-04-21 +- **Content updates**: +- Added 301 response for `ListIdentifiers` and `GetIdentifier` +- Added 308 response for `DeleteProfile`, `CreateIdentifier`, `PatchIdentifier`, and `DeleteIdentifier` +- ## 2026-04-14 +- **Modified 1 path(s)**: +- `/v1/ControlPlane/Stores/{storeId}` (added delete) +- Minor updates (formatting, metadata) + +**Voice** +- ## 2026-04-17 +- Added `I-Twilio-Auth-Account` to `downstreamRequest` headers in POST /v3/Transcriptions transactions to document RestProxy account header injection +- ## 2026-04-10 +- Added initial version of Transcriptions V3 API +- Added POST /v3/Transcriptions endpoint to create a new transcription from a source ID or media URL + + +[2026-04-14] Version 9.10.5 +--------------------------- +**Twiml** +- Add `backgroundNoiseReduction`, `speechTimeout`, `deepgramSmartFormat`, `ignoreBackchannel`, `events` attributes to `` + +**Api** +- Enabled incoming phone numbers(IPN) public apis in stage-ie1 + +**Data-ingress** +- ## 2026-04-09 +- **Content updates**: +- Added parameter(s) to `GetDataSync`: datasetId +- ## 2026-04-09 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- Minor updates (formatting, metadata) +- ## 2026-04-06 +- **Content updates**: +- Added properties to `CloudAppSourceUpdate`: config +- Added properties to `CloudAppDatasetUpdate`: schedule +- Added properties to `WarehouseSourceUpdate`: config +- Added properties to `WarehouseDatasetUpdate`: schedule +- ## 2026-04-06 +- **Content updates**: +- Updated description for `GetCloudAppPreviewResult` +- Updated description for `GetWarehousePreviewResult` +- Updated description for `GetDataSampleResult` +- ## 2026-03-27 +- Add schema oneOf back without discriminator +- ## 2026-03-26 +- Minor updates (formatting, metadata) +- ## 2026-03-26 +- Added prod-us1 to supportedRealms for all endpoints +- ## 2026-03-25 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- **Added 10 new path(s)**: +- `/v1/DataSyncs` (ListDataSyncs, TriggerDataSync) +- `/v1/DataSyncs/{SyncId}` (GetDataSync) +- `/v1/CloudAppSources/{SourceId}/Objects` (ListCloudAppObjects) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Properties` (ListCloudAppObjectProperties) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Preview` (PreviewCloudAppObjectData) +- `/v1/CloudAppSources/{SourceId}/Objects/{Name}/Preview/{OperationId}` (GetCloudAppPreviewResult) +- `/v1/WarehouseSources/{SourceId}/Preview` (PreviewWarehouseData) +- `/v1/WarehouseSources/{SourceId}/Preview/{OperationId}` (GetWarehousePreviewResult) +- `/v1/DataSample` (TriggerDataSample) +- `/v1/DataSample/{OperationId}` (GetDataSampleResult) +- ## 2026-03-24 +- Minor updates (formatting, metadata) +- ## 2026-03-24 +- Use `explode: true` for query params when getting by ids and limit max items to 25 +- Make schema description for `Schema` more specific by using oneOf without discriminator for now. + +**Insights** +- Added Insights Domains endpoints under `/v3/InsightsDomains/*` (Query + Metadata) to provide a versioned, GA-ready namespace alongside existing `/preview` endpoints. + +**Mcp** +- # API Changes +- ## 2026-04-07 +- **Added 1 new path(s)**: +- `/v1/docs` (InvokeDocsMcp) + +**Memory** +- ## 2026-04-09 +- **Removed 2 path(s)**: +- `/v1/Stores/{storeId}/Profiles/Import` (ListProfileImports, CreateProfilesImport) +- `/v1/Stores/{storeId}/Profiles/Import/{importId}` (FetchProfileImport) +- libraryVisibility: private, docsVisibility: private +- ## 2026-04-08 +- **Content updates**: +- Added 301 response for `GetProfile` and `GetProfileTraits` +- Added canonical ID header to response for `GetProfile` and `GetProfileTraits` +- Add 308 response for `PatchProfile` +- ## 2026-04-07 +- Added `AGENT` and `UNKNOWN` values to `ParticipantType` enum +- ## 2026-04-06 +- **Content updates**: +- Added async operation support to `UpdateTraitGroup` 202 response (Operation-Id, Location, Retry-After headers; statusUrl in body) +- Added async operation support to `CreateDataMapping`, `UpdateDataMapping`, `DeleteDataMapping` 202 responses (Operation-Id, Location, Retry-After headers; statusUrl in body) +- ## 2026-03-30 +- **Content updates**: +- Updated description for `FetchProfileMemory` +- ## 2026-03-27 +- **Content updates**: +- Updated schema description for `TraitGroupCore` +- ## 2026-03-25 +- **Content updates**: +- Removed properties from `TraitDefinition`: displayName +- ## 2026-03-25 +- **Content updates**: +- Updated description for `UpdateProfileTraits` +- Updated description for `FetchIdentityResolutionSettings` +- Updated description for `UpdateIdentityResolutionSettings` +- Updated schema description for `IdentityResolutionSettingsCore` +- Updated schema description for `TraitGroupCore` +- Made all fields besides `idType` optional w/ defaults for schema `IdentifierConfig` +- ## 2026-03-24 +- **Content updates**: +- Added properties to `OperationStatus`: result + + +[2026-03-24] Version 9.10.4 +--------------------------- +**Data-ingress** +- # API Changes +- ## 2026-03-23 +- Added stage-us1 to supportedRealms for all endpoints +- ## 2026-03-20 +- **Content updates**: +- Removed estimatedCompletionTime from `LongRunningOperationResponse` +- Moved operationId from `LongRunningOperationResponse` to headers +- ## 2026-03-18 +- **Added 1 new path(s)**: +- `/v1/ControlPlane/Operations/{OperationId}` (GetControlPlaneOperationStatus) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-11 +- Minor updates (formatting, metadata) +- ## 2026-03-05 +- Initial release with 10 paths and 22 operations + +**Memory** +- ## 2026-03-19 +- **Added 1 new path(s)**: +- `/v1/ControlPlane/Operations/{operationId}` (FetchOperation) +- ## 2026-03-11 +- Minor updates (formatting, metadata) + + +[2026-03-10] Version 9.10.3 +--------------------------- +**Twiml** +- Rename `recording_configuration` to `recording_configuration_id` attribute in ``, ``, `` verbs and `` noun + +**Ace** +- # ACE Signals API Changes +- ## 2026-02-18 +- Initial release: POST /signals, GET/POST /signals/{signal_id}/results, GET /health +- Enables OneAdmin integration for synchronous signal ingestion and policy result polling +- Supports permission-based authorization for signal operations +- Health endpoint available for monitoring without authentication + +**Api** +- Added optional parameter `Confirmation` to Payments create endpoint to enable payment confirmation prompt before gateway submission +- Added optional parameter `RequireMatchingInputs` to Payments create endpoint for input confirmation in agent-assisted payment flows +- Added matcher capture types (`payment-card-number-matcher`, `expiration-date-matcher`, `security-code-matcher`, `postal-code-matcher`) to Payments update endpoint + +**Memory** +- ## 2026-03-06 +- **Modified 1 path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/ConversationSummaries/{summaryId}` (added patch, get) + + +[2026-02-18] Version 9.10.2 +--------------------------- +**Api** +- Remove inequality examples from Calls StartTime and EndTime filter descriptions + +**Memory** +- ## 2026-02-06 +- Minor updates (formatting, metadata) +- ## 2026-02-06 +- Minor updates (formatting, metadata) +- ## 2026-02-06 +- ## 2026-01-23 +- ## 2026-01-23 +- **Added 3 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/Imports` (ListProfileImportsV2, CreateProfilesImportV2) +- `/v1/Stores/{storeId}/Profiles/Imports/{importId}` (FetchProfileImportV2) +- **Removed 6 path(s)**: +- `/v1/KnowledgeBases/{kbId}/Knowledge` (ListKnowledge, CreateKnowledge) +- `/v1/KnowledgeBases/{kbId}/Search` (KnowledgeSearch) +- `/v1/KnowledgeBases/{kbId}/Knowledge/{knowledgeId}` (RetrieveKnowledge, PatchKnowledge, DeleteKnowledge) +- `/v1/KnowledgeBases/{kbId}/Knowledge/{knowledgeId}/Chunks` (ListKnowledgeChunks) +- `/v1/ControlPlane/KnowledgeBases` (ListKnowledgeBases, CreateKnowledgeBase) +- `/v1/ControlPlane/KnowledgeBases/{kbId}` (GetKnowledgeBase, UpdateKnowledgeBase, DeleteKnowledgeBase) +- ## 2026-01-05 +- ## 2026-01-05 +- Initial release with 26 paths and 48 operations + + +[2026-02-05] Version 9.10.1 +--------------------------- +**Library - Fix** +- [PR #907](https://github.com/twilio/twilio-python/pull/907): Regional API domain processing. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Twiml** +- Add `recording_configuration` attribute to `` noun + +**Api** +- Clarify the behavior of date filters with the Calls API +- Added Phone Number `type` property to `/IncomingPhoneNumbers` resource + +**Memory** +- ## 2026-01-23 +- No path changes (updated metadata only) +- ## 2026-01-22 +- No path changes (updated metadata only) +- ## 2026-01-22 +- **Modified 1 path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}` (added delete) + + +[2026-01-22] Version 9.10.0 +--------------------------- +**Library - Feature** +- [PR #896](https://github.com/twilio/twilio-python/pull/896): Token pagination support. Thanks to [@kridai](https://github.com/kridai)! +- [PR #902](https://github.com/twilio/twilio-python/pull/902): add support for response headers. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Chore** +- [PR #904](https://github.com/twilio/twilio-python/pull/904): fix lint errors. Thanks to [@kridai](https://github.com/kridai)! +- [PR #901](https://github.com/twilio/twilio-python/pull/901): Error response changes. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Fix** +- [PR #903](https://github.com/twilio/twilio-python/pull/903): allow nullable headers response field. Thanks to [@kridai](https://github.com/kridai)! + +**Twiml** +- Added support for and inside + +**Assistants** +- AI Assistants v1 release + +**Autopilot** +- Remove Export resource from Autopilot Assistant +- Add dialogue_sid param to Query list resource +- Add Restore resource to Autopilot Assistant +- Add one new property in Query i.e dialogue_sid +- Add Export resource to Autopilot Assistant. +- Adds two new properties in Assistant i.e needs_model_build and development_stage +- Add Webhooks resource to Autopilot Assistant. +- Introduce `autopilot` subdomain with all resources from `preview.understand` + +**Compliance** +- Added the new InventoryComplianceInsights API under version `/v1`. + +**Content** +- changes for adding v2 endpoints + +**Marketplace** +- Initial transition to Marketplace domain + +**Memory** +- # API Changes +- ## 2026-01-15 +- No path changes (updated metadata only) +- ## 2026-01-13 +- **Added 1 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/ConversationSummaries/{summaryId}` (DeleteProfileConversationSummary) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- No path changes (updated metadata only) +- ## 2026-01-12 +- **Added 2 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/Imports` (ListProfileImportsV2, ImportProfilesV2) +- `/v1/Stores/{storeId}/Profiles/Imports/{importId}` (GetProfileImportV2) +- ## 2026-01-13 +- No path changes (updated metadata only) +- ## 2026-01-07 +- No path changes (updated metadata only) +- ## 2026-01-05 +- No path changes (updated metadata only) +- ## 2025-12-17 +- No path changes (updated metadata only) +- ## 2025-12-17 +- No path changes (updated metadata only) +- ## 2025-12-17 +- **Added 1 new path(s)**: +- `/v1/Stores/{storeId}/Profiles/{profileId}/Observations/{observationId}/Revisions` (ListObservationRevisions) + +**Sender-ids** +- Added all v2 sender-id-service endpoints + +**Trusthub** +- Add new delete endpoint for compliance_registration. + +**Voice** +- Add ProvisioningStatus public API endpoints. + +**Wise_owl** +- Init API as open-api spec +- Updated Get Chat, Send Message and Create Chat to include `contexts` in Message, instead of root Chat + +**Www** +- Port APIs from oauth.twilio.com to www.twilio.com + + +[2026-01-07] Version 9.9.1 +-------------------------- +**Api** +- Added optional parameter `clientNotificationUrl` for create call api +- Added optional parameter `clientNotificationUrl` for create participant api + + +[2025-12-17] Version 9.9.0 +-------------------------- +**Library - Fix** +- [PR #898](https://github.com/twilio/twilio-python/pull/898): allow 2XX response for delete operation. Thanks to [@kridai](https://github.com/kridai)! + +**Trunking** +- Corrected the type used for phone number capabilities when accessed through a Trunk. **(breaking change)** +- Corrected the type used for phone number capabilities when accessed through a Trunk. **(breaking change)** + +**Trusthub** +- Added new parameters in in toll-free initialize api payload. +- Remove the invalid status transition to Draft from the examples +- Change the value of email to a valid one in the examples. + + +[2025-12-03] Version 9.8.8 +-------------------------- +**Library - Fix** +- [PR #895](https://github.com/twilio/twilio-python/pull/895): Regional API domain processing. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Add `twiml_session` resource for calls +- Add `twiml_session` resource for calls + +**Monitor** +- Update default output properties + +**Trusthub** +- Added customer_profile_sid in toll-free initialize api payload. + + +[2025-11-20] Version 9.8.7 +-------------------------- +**Memory** +- # Memory API Changes +- Added initial Memory API endpoints with darkseagreen badge status + + +[2025-11-11] Version 9.8.6 +-------------------------- +**Twiml** +- Add new noun `` +- Add support for `` noun under `` verb + + +[2025-10-28] Version 9.8.5 +-------------------------- +**Ai** +- Add `error` as possible transcript status +- Add `error` as possible transcript status + +**Chat** +- Updated v2 UserChannel `channel_status` from `not_participating` to `notParticipating` + +**Intelligence** +- Make intelligence work with RestProxy +- Add additional enums to better represent the possible states +- Add `error` enum to transcription status to better align with possible outputs +- Add `json` output type to text classification + +**Trusthub** +- Remove required parameter Primary Profile Sid from compliance_inquiry and compliance_inquiry_individual + +**Accounts** +- Add Messaging GeoPermissions API changes + + +[2025-10-14] Version 9.8.4 +-------------------------- +**Library - Chore** +- [PR #887](https://github.com/twilio/twilio-python/pull/887): remove auth from request.__str__(). Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Docs** +- [PR #886](https://github.com/twilio/twilio-python/pull/886): update oauth example. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated description for property `CallerDisplayName` for participant create request +- Updated description for property `CallerDisplayName` for participant create request + +**Accounts** +- FILE_IS_AUTO_GENERATED: false + + +[2025-09-30] Version 9.8.3 +-------------------------- +**Library - Chore** +- [PR #882](https://github.com/twilio/twilio-python/pull/882): change oauth token endpoint. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Insights** +- Replace `field` with `key` in Request Filters and Response Metadata Filters and for Reports API + + +[2025-09-25] Version 9.8.2 +-------------------------- +**Api** +- Added optional parameter `CallerDisplayName` for conference participant outbound +- Updated description for property `to` in the participant create request + + +[2025-09-18] Version 9.8.1 +-------------------------- +**Api** +- Add `date_created` property to media resource and date_created filtering parameters for read action +- Updated the Recordings Resource `channels` property to clarify channels = # of channels in the recording resource and how to specify the # of channels in recording download + +**Intelligence** +- Add encryption_credential_sid field in transcripts and services in v2 + +**Trusthub** +- Remove beta feature flag for all TH APIs +- Remove beta feature flag for ComplianceInquiries API to support OneConsole traffic + +**Twiml** +- Add new noun `` + + +[2025-09-04] Version 9.8.0 +-------------------------- +**Api** +- Remove usage category enum from usage record and usage triggers API **(breaking change)** + + +[2025-08-28] Version 9.7.2 +-------------------------- +**Studio** +- Add `type` to Step resource APIs + +**Verify** +- Allow to update all passkeys parameters in the service update + + +[2025-08-18] Version 9.7.1 +-------------------------- +**Accounts** +- Update beta feature flag for consent and contact bulk upsert APIs + +**Api** +- Add multiple missing usage categories to usage records and usage triggers api +- Add `channels-whatsapp-template-marketing` and `channels-whatsapp-template-utility` to usage categories + +**Conversations** +- Fix `state` spelling for `initializing` enum value +- Update `state` to include `intializing` for ServiceConversationWithParticipants and ConversationWithParticipants + +**Flex** +- Adding new optional parameter `identity` to `web_channels` API in version `v2` + +**Trusthub** +- Add required Permissions to the ComplianceInquiries API + +**Verify** +- Add passkeys support to Verify API creating and updating services. +- Update `ienum` type for Factor creation +- Add passkeys as challenge and factor type + + +[2025-07-24] Version 9.7.0 +-------------------------- +**Library - Fix** +- [PR #878](https://github.com/twilio/twilio-python/pull/878): Remove not existence class ServiceList. Thanks to [@lopenchi](https://github.com/lopenchi)! + +**Events** +- Remove `SinkSid` parameter when updating subscriptions. **(breaking change)** + +**Twiml** +- Remove Duplicates. +- Add Polly Generative voices. +- Add Latest Google (Chirp3-HD) voices. + + +[2025-07-10] Version 9.6.5 +-------------------------- +**Library - Fix** +- [PR #874](https://github.com/twilio/twilio-python/pull/874): delete non existing import in rest/preview. Thanks to [@lopenchi](https://github.com/lopenchi)! + +**Flex** +- update team name for web_channel, webchat_init_token, webchat_refresh_token + + +[2025-07-03] Version 9.6.4 +-------------------------- +**Library - Chore** +- [PR #865](https://github.com/twilio/twilio-python/pull/865): Remove references to microvisor. Thanks to [@akhani18](https://github.com/akhani18)! +- [PR #872](https://github.com/twilio/twilio-python/pull/872): support Python 3.13. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #870](https://github.com/twilio/twilio-python/pull/870): remove knowledge domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Bulkexports** +- Changed the type of 'details' field to be a list of objects instead of a single object + +**Conversations** +- Updates to `method` casing for ConfgurationAddress, ConversationScopedWebhook, and ServiceConversationScopedWebhook for RestProxy compatibility + +**Proxy** +- remove shortcodes resource as its no longer used + +**Serverless** +- Change log field level from type `ienum` to `string` in Logs api + +**Taskrouter** +- Remove `URL-encoded` from attributes param definition in tasks + +**Trunking** +- Added `symmetric_rtp_enabled` property on Trunks. + +**Twiml** +- Add support for `` noun under `` verb + + +[2025-06-12] Version 9.6.3 +-------------------------- +**Library - Chore** +- [PR #869](https://github.com/twilio/twilio-python/pull/869): Remove knowledge files. Thanks to [@krishnakalluri](https://github.com/krishnakalluri)! + +**Api** +- Change DependentPhoneNumber `capabilities` type `object` and `date_created`, `date_updated` to `date_time` +- Updated the `Default` value from 0 to 1 in the Recordings Resource `channels` property + +**Serverless** +- Update `ienum` type level in Logs api + +**Verify** +- Update Channel list in Verify Attempst API +- Update `ienum` type for Conversion_Status in Verify Attempts API + +**Twiml** +- Add `us2` to the list of supported values for the region attribute in the `` TwiML noun. + + +[2025-05-29] Version 9.6.2 +-------------------------- +**Library - Chore** +- [PR #862](https://github.com/twilio/twilio-python/pull/862): update iam token endpoint. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Added several usage category enums to `usage_record` API + +**Numbers** +- Update the porting documentation + +**Verify** +- Update `ienum` type for Channels in Verify Attempts API + + +[2025-05-13] Version 9.6.1 +-------------------------- +**Accounts** +- Changes to add date_of_consent param in Bulk Consent API + +**Api** +- Change `friendly_name`, `date_created` and `date_updated` properties to type `string`. + +**Twiml** +- Update twiml definition for `` and `` + + +[2025-05-05] Version 9.6.0 +-------------------------- +**Library - Fix** +- [PR #848](https://github.com/twilio/twilio-python/pull/848): Timezone changes in token_auth_strategy.py. Thanks to [@Pablo2113](https://github.com/Pablo2113)! +- [PR #853](https://github.com/twilio/twilio-python/pull/853): Fix deprecated/invalid config in `setup.cfg`. Thanks to [@abravalheri](https://github.com/abravalheri)! + +**Library - Chore** +- [PR #858](https://github.com/twilio/twilio-python/pull/858): fix oauth examples. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Docs** +- [PR #855](https://github.com/twilio/twilio-python/pull/855): update pagination usage in README.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Add `response_key` for `Usage Triggers` fetch endpoint. + +**Flex** +- Add Update Interaction API +- Adding `webhook_ttid` as optional parameter in Interactions API + +**Serverless** +- Add node22 as a valid Build runtime +- Add node20 as a valid Build runtime + +**Video** +- removed `transcribe_participants_on_connect` and `transcriptions_configuration` from the room resource **(breaking change)** +- Added `transcribe_participants_on_connect` and `transcriptions_configuration` to the room resource + + +[2025-04-07] Version 9.5.2 +-------------------------- +**Studio** +- Add documentation for parent_step_sid field in Step resource + + +[2025-03-20] Version 9.5.1 +-------------------------- +**Accounts** +- Update Safelist API docs as part of prefix supoort + +**Flex** +- Removing `first_name`, `last_name`, and `friendly_name` from the Flex User API + +**Messaging** +- Add missing tests under transaction/phone_numbers and transaction/short_code + + +[2025-03-11] Version 9.5.0 +-------------------------- +**Library - Feature** +- [PR #850](https://github.com/twilio/twilio-python/pull/850): Update UPGRADE.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Library - Fix** +- [PR #847](https://github.com/twilio/twilio-python/pull/847): AssistantsBase import. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add the missing `emergency_enabled` field for `Address Service` endpoints + +**Messaging** +- Add missing enums for A2P and TF + +**Numbers** +- add missing enum values to hosted_number_order_status + +**Twiml** +- Convert Twiml Attribute `speechModel` of type enum to string **(breaking change)** + + +[2025-02-20] Version 9.4.6 +-------------------------- +**Library - Chore** +- [PR #842](https://github.com/twilio/twilio-python/pull/842): issue 841. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Flex** +- Adding Digital Transfers APIs under v1/Interactions + +**Numbers** +- Convert webhook_type to ienum type in v1/Porting/Configuration/Webhook/{webhook_type} + +**Trusthub** +- Changing TrustHub SupportingDocument status enum from lowercase to uppercase since kyc-orch returns status capitalized and rest proxy requires strict casing + + +[2025-02-11] Version 9.4.5 +-------------------------- +**Api** +- Change downstream url and change media type for file `base/api/v2010/validation_request.json`. + +**Intelligence** +- Add json_results for Generative JSON operator results + +**Messaging** +- Add DestinationAlphaSender API to support Country-Specific Alpha Senders + +**Video** +- Change codec type from enum to case-insensitive enum in recording and room_recording apis + + +[2025-01-28] Version 9.4.4 +-------------------------- +**Library - Fix** +- [PR #822](https://github.com/twilio/twilio-python/pull/822): Fix for 10 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Chore** +- [PR #834](https://github.com/twilio/twilio-python/pull/834): update httpclient. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #837](https://github.com/twilio/twilio-python/pull/837): enable newer versions of aiohttp-retry. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #833](https://github.com/twilio/twilio-python/pull/833): created bug report issue template. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add open-api file tag to `conference/call recordings` and `recording_transcriptions`. + +**Events** +- Add support for subaccount subscriptions (beta) + +**Insights** +- add new region to conference APIs + +**Lookups** +- Add new `parnter_sub_id` query parameter to the lookup request + + [2025-01-13] Version 9.4.3 -------------------------- **Messaging** diff --git a/README.md b/README.md index bfbd6a14b5..6c25c0a81e 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,10 @@ The Python library documentation can be found [here][libdocs]. This library supports the following Python implementations: -- Python 3.7 -- Python 3.8 -- Python 3.9 - Python 3.10 - Python 3.11 +- Python 3.12 +- Python 3.13 ## Installation @@ -87,7 +86,7 @@ After a brief delay, you will receive the text message on your phone. > It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out [How to Set Environment Variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) for more information. ## OAuth Feature for Twilio APIs -We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change. +We are introducing Client Credentials Flow-based OAuth 2.0 authentication. API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) @@ -135,7 +134,9 @@ client = Client() ### Specify Region and/or Edge -To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and/or Edge for the client: +To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and Edge for the client: + +> **Note:** When specifying a `region` parameter for a helper library client, be sure to also specify the `edge` parameter. For backward compatibility purposes, specifying a `region` without specifying an `edge` will result in requests being routed to US1. ```python from twilio.rest import Client @@ -191,6 +192,8 @@ The library automatically handles paging for you. Collections, such as `calls` a `list` eagerly fetches all records and returns them as a list, whereas `stream` returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the `page` method. +`page_size` as a parameter is used to tell how many records should we get in every page and `limit` parameter is used to limit the max number of records we want to fetch. + #### Use the `list` method ```python @@ -204,6 +207,21 @@ for sms in client.messages.list(): print(sms.to) ``` +```python +client.messages.list(limit=20, page_size=20) +``` +This will make 1 call that will fetch 20 records from backend service. + +```python +client.messages.list(limit=20, page_size=10) +``` +This will make 2 calls that will fetch 10 records each from backend service. + +```python +client.messages.list(limit=20, page_size=100) +``` +This will make 1 call which will fetch 100 records but user will get only 20 records. + ### Asynchronous API Requests By default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying `*_async` methods, requests made to the Twilio API will be performed asynchronously. diff --git a/docs/conf.py b/docs/conf.py index 017b358093..3e1b634387 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,7 +19,6 @@ sys.path.insert(0, os.path.abspath("..")) from twilio import __version__ - # -- Project information ----------------------------------------------------- project = "twilio-python" diff --git a/examples/client_validation.py b/examples/client_validation.py index a7bc08e81a..7f2e42c58b 100644 --- a/examples/client_validation.py +++ b/examples/client_validation.py @@ -12,7 +12,6 @@ from twilio.http.validation_client import ValidationClient from twilio.rest import Client - ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") diff --git a/examples/organization_api.py b/examples/organization_api.py index 180f18c20b..0d653c12a4 100644 --- a/examples/organization_api.py +++ b/examples/organization_api.py @@ -16,12 +16,12 @@ def example(): """ Some example usage of using organization resources """ - self.client = Client( + client = Client( account_sid=ACCOUNT_SID, credential_provider=OrgsCredentialProvider(CLIENT_ID, CLIENT_SECRET), ) - accounts = self.client.preview_iam.organization( + accounts = client.preview_iam.organization( organization_sid=ORGS_SID ).accounts.stream() for record in accounts: diff --git a/examples/public_oauth.py b/examples/public_oauth.py index 527961f4e3..124531fc46 100644 --- a/examples/public_oauth.py +++ b/examples/public_oauth.py @@ -4,27 +4,24 @@ from twilio.credential.client_credential_provider import ClientCredentialProvider ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") -API_KEY = os.environ.get("TWILIO_API_KEY") -API_SECRET = os.environ.get("TWILIO_API_SECRET") -FROM_NUMBER = os.environ.get("TWILIO_FROM_NUMBER") -TO_NUMBER = os.environ.get("TWILIO_TO_NUMBER") +MESSAGE_SID = os.environ.get("TWILIO_MESSAGE_SID") CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") -CLIENT_SECRET = os.environ.get("CLIENT_SECRET") +CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET") def example(): """ - Some example usage of message resources. + An example usage of message resource. """ - self.client = Client( + client = Client( account_sid=ACCOUNT_SID, credential_provider=ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET), ) - msg = self.client.messages.create( - to=self.to_number, from_=self.from_number, body="hello world" - ) + msg = client.messages(MESSAGE_SID).fetch() + + print(msg) if __name__ == "__main__": diff --git a/release-plan.md b/release-plan.md new file mode 100644 index 0000000000..570079c913 --- /dev/null +++ b/release-plan.md @@ -0,0 +1,96 @@ +# Twilio Python SDK — Release Plan + +## ci.yml (CI) + +**Triggers:** PRs to main | Push to main | Manual dispatch | Cron (Monday 9AM IST) + +### Jobs + +1. **lockfile-hygiene** _(all triggers)_ + - Checkout + - [`uv-lockfile-hygiene`](https://github.com/twilio/sdk-actions/blob/main/uv-lockfile-hygiene/action.yml) action (scan only, no clean-room install) + - Fails if internal Artifactory hosts found in `requirements*.txt` + +2. **test** (Python matrix) — _needs: lockfile-hygiene_ _(all triggers)_ + - Checkout + - [Artifactory OIDC Auth](https://github.com/twilio/sdk-actions/tree/main/artifactory-oidc) (`ecosystem: python`) + - Setup Python + - `pip install virtualenv` + `make install test-install` + `make prettier` + - `make test-with-coverage` + - Cluster tests (`make cluster-test` with 7 secrets) + - Verify docs generation (`make docs`) + - Matrix: `3.12` on PRs/pushes, `[3.8–3.13]` on cron/manual with `all` + +3. **deploy-dry-run** (Release Readiness Check - Build artifact) — _needs: test_ _(cron + manual dispatch only)_ + - Checkout + - Artifactory OIDC Auth + - Setup Python 3.12 + - Validate version format is semver (`X.Y.Z`) + - Build sdist + wheel (`python -m build`) + - Verify with `twine check dist/*` + - List artifacts + print summary + - **Does NOT publish** + +--- + +## deploy.yml — Publish to PyPI + +**Trigger:** Tag push matching `v*` + +### How to release + +1. Bump `version` in `setup.py`, merge to `main` +2. Tag and push: `git tag v9.0.1 && git push --tags` +3. Workflow fires automatically +4. Approve the `production` environment gate when prompted +5. Verify: `pip install twilio==9.0.1` + check attestations on pypi.org + +### Jobs + +1. **lockfile-hygiene** + - Checkout + - [`uv-lockfile-hygiene`](https://github.com/twilio/sdk-actions/blob/main/uv-lockfile-hygiene/action.yml) scan (no clean-room install) + +2. **test** (Python 3.8–3.13 full matrix) — _needs: lockfile-hygiene_ + - Checkout + - [Artifactory OIDC Auth](https://github.com/twilio/sdk-actions/tree/main/artifactory-oidc) (`ecosystem: python`) + - Setup Python + - `pip install virtualenv` + `make install test-install` + `make prettier` + - `make test-with-coverage` + +3. **deploy** (Publish to PyPI) — _needs: test, requires `production` env approval_ + - Checkout + - Create GitHub Release (auto-generated notes) + - Artifactory OIDC Auth + - Setup Python 3.12 + - Validate tag format (`vX.Y.Z`) + matches `setup.py` version + - Build sdist + wheel (`python -m build`) + - Verify with `twine check dist/*` + - Publish to PyPI (OIDC trusted publishing, PEP 740 attestations) + +--- + +## End-to-end Release Day Flow + +| Step | Action | +| --- | --- | +| Weekly | Monday cron runs CI workflow — confirms infra is healthy (full matrix + dry run) | +| On every PR | CI workflow runs lockfile-hygiene + test (3.12) + cluster tests + docs | +| 1 | [ **_Librarian_** ] PR: bump `setup.py` version, merge to `main` | +| 2 | [ **_Librarian_** ] `git tag vX.Y.Z && git push --tags` | +| 3 | `deploy.yml` fires automatically on tag creation, tests run (3.8–3.13) | +| 4 | [ **_Manual_** ] Approve `production` environment gate | +| 5 | GitHub Release created, package published to PyPI | +| 6 | [ **_Manual_** ] Verify: `pip install twilio==X.Y.Z` + check attestations on pypi.org | + +--- + +## Platform Team Dependencies + +| Dependency | Owner | Breaks if... | +| --- | --- | --- | +| Artifactory OIDC provider (`github-actions`) | SSC / Platform | Repo renamed, org changed, trust not configured | +| `vars.ARTIFACTORY_URL` | Repo admin | Variable not set or URL changes | +| `production` GitHub environment | Repo admin | Environment doesn't exist or approvals misconfigured | +| `ubuntu-x64` runner group | Enterprise admin | Repo not added to runner group, or runner pool down | +| PyPI trusted publisher | PyPI org admin | Not registered, or workflow filename / environment mismatch | diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000000..7bc9e41806 --- /dev/null +++ b/requirements.in @@ -0,0 +1,8 @@ +pygments>=2.7.4 # not directly required, pinned by Snyk to avoid a vulnerability +requests>=2.32.2 +PyJWT>=2.0.0, <3.0.0 +aiohttp>=3.10.2 +aiohttp-retry==2.8.3 +certifi>=2023.7.22 # not directly required, pinned by Snyk to avoid a vulnerability +urllib3>=2.2.2 # not directly required, pinned by Snyk to avoid a vulnerability +zipp>=3.19.1 # not directly required, pinned by Snyk to avoid a vulnerability diff --git a/requirements.txt b/requirements.txt index 3de95e70c9..19de7b687c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,54 @@ -pygments>=2.7.4 # not directly required, pinned by Snyk to avoid a vulnerability -requests>=2.31.0 -PyJWT>=2.0.0, <3.0.0 -aiohttp>=3.9.4 +# +# This file is autogenerated by pip-compile with Python 3.14 +# by the following command: +# +# pip-compile --output-file=requirements.txt requirements.in +# +aiohappyeyeballs==2.6.2 + # via aiohttp +aiohttp==3.14.1 + # via + # -r requirements.in + # aiohttp-retry aiohttp-retry==2.8.3 -certifi>=2023.7.22 # not directly required, pinned by Snyk to avoid a vulnerability + # via -r requirements.in +aiosignal==1.4.0 + # via aiohttp +attrs==26.1.0 + # via aiohttp +certifi==2026.5.20 + # via + # -r requirements.in + # requests +charset-normalizer==3.4.7 + # via requests +frozenlist==1.8.0 + # via + # aiohttp + # aiosignal +idna==3.18 + # via + # requests + # yarl +multidict==6.7.1 + # via + # aiohttp + # yarl +propcache==0.5.2 + # via + # aiohttp + # yarl +pygments==2.20.0 + # via -r requirements.in +pyjwt==2.13.0 + # via -r requirements.in +requests==2.34.2 + # via -r requirements.in +urllib3==2.7.0 + # via + # -r requirements.in + # requests +yarl==1.24.2 + # via aiohttp +zipp==4.1.0 + # via -r requirements.in diff --git a/setup.cfg b/setup.cfg index 0df04dde4d..4c18756789 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,7 +2,7 @@ universal = 1 [metadata] -description-file = README.md +long_description = file: README.md license = MIT [flake8] diff --git a/setup.py b/setup.py index 229d8e1ebe..c315083711 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ setup( name="twilio", - version="9.4.3", + version="9.11.0", description="Twilio API client and TwiML generator", author="Twilio", help_center="https://www.twilio.com/help/contact", @@ -24,7 +24,7 @@ "requests >= 2.0.0", "PyJWT >= 2.0.0, < 3.0.0", "aiohttp>=3.8.4", - "aiohttp-retry==2.8.3", + "aiohttp-retry>=2.8.3", ], packages=find_packages(exclude=["tests", "tests.*"]), include_package_data=True, @@ -39,6 +39,8 @@ "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 :: Implementation :: CPython", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", diff --git a/tests/holodeck.py b/tests/holodeck.py index 8f71514314..81db67683b 100644 --- a/tests/holodeck.py +++ b/tests/holodeck.py @@ -1,5 +1,5 @@ from twilio.base.exceptions import TwilioRestException -from twilio.http import HttpClient +from twilio.http import HttpClient, AsyncHttpClient from twilio.http.request import Request import platform from twilio import __version__ @@ -15,6 +15,7 @@ class Holodeck(HttpClient): def __init__(self): self._holograms = [] self._requests = [] + self.is_async = False def mock(self, response, request=None): request = request or Request() @@ -87,3 +88,86 @@ def request( message += "No Holograms loaded" raise TwilioRestException(404, url, message, method=method) + + +class AsyncHolodeck(AsyncHttpClient): + """Async version of Holodeck for async testing""" + + def __init__(self): + # Don't call super().__init__() to avoid logger requirement + self._holograms = [] + self._requests = [] + self.is_async = True + + def mock(self, response, request=None): + request = request or Request() + self._holograms.append(Hologram(request, response)) + + @property + def requests(self): + return self._requests + + def add_standard_headers(self, request): + standard_headers = { + "User-Agent": "twilio-python/{} ({} {}) Python/{}".format( + __version__, + platform.system(), + platform.machine(), + platform.python_version(), + ), + "X-Twilio-Client": "python-{}".format(__version__), + "Accept": "application/json", + "Accept-Charset": "utf-8", + } + + if request.method == "POST" and "Content-Type" not in standard_headers: + standard_headers["Content-Type"] = "application/x-www-form-urlencoded" + + standard_headers.update(request.headers) + request.headers = standard_headers + return request + + def assert_has_request(self, request): + for req in self.requests: + if req == request or req == self.add_standard_headers(request): + return + + message = "\nHolodeck never received a request matching: \n + {}\n".format( + request + ) + if self._requests: + message += "Requests received:\n" + message += "\n".join(" * {}".format(r) for r in self.requests) + else: + message += "No Requests received" + + raise AssertionError(message) + + async def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + """Async request method""" + request = Request(method, url, auth, params, data, headers) + + self._requests.append(request) + + for hologram in self._holograms: + if hologram.request == request: + return hologram.response + + message = "\nHolodeck has no hologram for: {}\n".format(request) + if self._holograms: + message += "Holograms loaded:\n" + message += "\n".join(" - {}".format(h.request) for h in self._holograms) + else: + message += "No Holograms loaded" + + raise TwilioRestException(404, url, message, method=method) diff --git a/tests/unit/base/test_token_pagination.py b/tests/unit/base/test_token_pagination.py new file mode 100644 index 0000000000..2de67831cd --- /dev/null +++ b/tests/unit/base/test_token_pagination.py @@ -0,0 +1,749 @@ +import unittest +from unittest.mock import Mock +from tests import IntegrationTestCase +from tests.holodeck import Request +from twilio.base.exceptions import TwilioException +from twilio.base.token_pagination import TokenPagination +from twilio.http.response import Response + + +class MockTokenPaginationPage(TokenPagination): + """Mock implementation of TokenPagination for testing""" + + def get_instance(self, payload): + return payload + + +class TokenPaginationPropertyTest(unittest.TestCase): + """Test TokenPagination property accessors""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + + # Mock response with token pagination format + self.payload = { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789", + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}], + } + + self.response = Mock() + self.response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789" + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """ + self.response.status_code = 200 + + self.solution = { + "account_sid": "ACxxxx", + } + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_key_property(self): + """Test that key property returns the correct value""" + self.assertEqual(self.page.key, "items") + + def test_page_size_property(self): + """Test that page_size property returns the correct value""" + self.assertEqual(self.page.page_size, 50) + + def test_next_token_property(self): + """Test that next_token property returns the correct value""" + self.assertEqual(self.page.next_token, "next_abc123") + + def test_previous_token_property(self): + """Test that previous_token property returns the correct value""" + self.assertEqual(self.page.previous_token, "prev_xyz789") + + def test_properties_without_meta(self): + """Test that properties return None when meta is missing""" + response = Mock() + response.text = '{"items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertIsNone(page.key) + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + def test_properties_with_partial_meta(self): + """Test that properties return None when specific keys are missing""" + response = Mock() + response.text = '{"meta": {"key": "items"}, "items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertEqual(page.key, "items") + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + +class TokenPaginationNavigationTest(IntegrationTestCase): + """Test TokenPagination next_page and previous_page methods""" + + def setUp(self): + super(TokenPaginationNavigationTest, self).setUp() + + # Mock first page response + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={}, + ), + ) + + # Mock second page response (next page) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page2"}, + ), + ) + + # Mock third page response (has no next) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev2" + }, + "items": [{"id": 5, "name": "Item 5"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page3"}, + ), + ) + + # Mock previous page response (going back to page 1) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev1"}, + ), + ) + + # Mock going back from page 3 to page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev2"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Resources.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Resources.json", + {}, + self.solution, + ) + + def test_next_page(self): + """Test that next_page() navigates to the next page using token""" + self.assertIsNotNone(self.page.next_token) + self.assertEqual(self.page.next_token, "token_page2") + + next_page = self.page.next_page() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + # Verify we got the next page's data + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev1") + + def test_next_page_none_when_no_token(self): + """Test that next_page() returns None when there's no next token""" + # Navigate to the last page + next_page = self.page.next_page() + last_page = next_page.next_page() + + # Last page should have no next token + self.assertIsNone(last_page.next_token) + + # next_page() should return None + result = last_page.next_page() + self.assertIsNone(result) + + def test_previous_page(self): + """Test that previous_page() navigates to the previous page using token""" + # Navigate to second page first + next_page = self.page.next_page() + self.assertIsNotNone(next_page.previous_token) + self.assertEqual(next_page.previous_token, "token_prev1") + + # Go back to previous page + prev_page = next_page.previous_page() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + # Verify we got the first page's data + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + def test_previous_page_none_when_no_token(self): + """Test that previous_page() returns None when there's no previous token""" + # First page should have no previous token + self.assertIsNone(self.page.previous_token) + + # previous_page() should return None + result = self.page.previous_page() + self.assertIsNone(result) + + def test_navigation_chain(self): + """Test navigating through multiple pages forward and backward""" + # Page 1 -> Page 2 + page2 = self.page.next_page() + self.assertEqual(page2.previous_token, "token_prev1") + + # Page 2 -> Page 3 + page3 = page2.next_page() + self.assertIsNone(page3.next_token) + self.assertEqual(page3.previous_token, "token_prev2") + + # Page 3 -> Page 2 (backward) + back_to_page2 = page3.previous_page() + self.assertIsNotNone(back_to_page2) + + +class TokenPaginationErrorTest(unittest.TestCase): + """Test TokenPagination error handling""" + + def test_next_page_without_uri_in_solution(self): + """Test that next_page() raises error when URI is missing""" + version = Mock() + response = Mock() + response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "abc123" + }, + "items": [] + } + """ + response.status_code = 200 + + # Solution without URI + solution = {"account_sid": "ACxxxx"} + + # Pass empty string as URI to test the error case + page = MockTokenPaginationPage(version, response, "", {}, solution) + + with self.assertRaises(TwilioException) as context: + page.next_page() + + self.assertIn("URI must be provided", str(context.exception)) + + +class TokenPaginationStreamTest(IntegrationTestCase): + """Test streaming with TokenPagination""" + + def setUp(self): + super(TokenPaginationStreamTest, self).setUp() + + # Mock page 1 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_2" + }, + "records": [{"id": 1}, {"id": 2}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={}, + ), + ) + + # Mock page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_3", + "previousToken": "token_2" + }, + "records": [{"id": 3}, {"id": 4}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_2"}, + ), + ) + + # Mock page 3 (final) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_3" + }, + "records": [{"id": 5}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_3"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Records.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Records.json", + {}, + self.solution, + ) + + def test_stream_all_records(self): + """Test streaming through all pages""" + records = list(self.version.stream(self.page)) + + self.assertEqual(len(records), 5) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[4]["id"], 5) + + def test_stream_with_limit(self): + """Test streaming with a limit""" + records = list(self.version.stream(self.page, limit=3)) + + self.assertEqual(len(records), 3) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[2]["id"], 3) + + def test_stream_with_page_limit(self): + """Test streaming with page limit""" + records = list(self.version.stream(self.page, page_limit=1)) + + # Only first page (2 records) + self.assertEqual(len(records), 2) + + +class TokenPaginationInternalMethodTest(unittest.TestCase): + """Test TokenPagination internal methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_get_page_with_valid_token(self): + """Test _get_page() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = self.page._get_page("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + def test_get_page_with_none_token(self): + """Test _get_page() with None token returns None""" + result = self.page._get_page(None) + self.assertIsNone(result) + + def test_get_page_without_uri(self): + """Test _get_page() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + page._get_page("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + def test_repr(self): + """Test __repr__ method returns correct string""" + self.assertEqual(repr(self.page), "") + + def test_params_preserved_across_pagination(self): + """Test that initial query params are preserved when fetching next page""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = page_with_params._get_page("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +class TokenPaginationAsyncTest(unittest.IsolatedAsyncioTestCase): + """Test TokenPagination async methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + # Mock previous page response + self.prev_response = Mock() + self.prev_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.prev_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + + # Page with next token + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + # Page with previous token (page 2) + self.page_with_prev = MockTokenPaginationPage( + self.version, + self.next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + async def test_get_page_async_with_valid_token(self): + """Test _get_page_async() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = await self.page._get_page_async("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + async def test_get_page_async_with_none_token(self): + """Test _get_page_async() with None token returns None""" + result = await self.page._get_page_async(None) + self.assertIsNone(result) + + async def test_get_page_async_without_uri(self): + """Test _get_page_async() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + await page._get_page_async("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + async def test_next_page_async(self): + """Test next_page_async() navigates to next page""" + self.version.page = Mock(return_value=self.next_response) + + next_page = await self.page.next_page_async() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev") + + async def test_next_page_async_none_when_no_token(self): + """Test next_page_async() returns None when there's no next token""" + # Create page with no next token + no_next_response = Mock() + no_next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 5}] + } + """ + no_next_response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, + no_next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + result = await page.next_page_async() + self.assertIsNone(result) + + async def test_previous_page_async(self): + """Test previous_page_async() navigates to previous page""" + self.version.page = Mock(return_value=self.prev_response) + + prev_page = await self.page_with_prev.previous_page_async() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + async def test_previous_page_async_none_when_no_token(self): + """Test previous_page_async() returns None when there's no previous token""" + # First page has no previous token + result = await self.page.previous_page_async() + self.assertIsNone(result) + + async def test_params_preserved_across_pagination_async(self): + """Test that initial query params are preserved when fetching next page async""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = await page_with_params._get_page_async("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/base/test_version.py b/tests/unit/base/test_version.py index 1f1f6395eb..03c684a2ff 100644 --- a/tests/unit/base/test_version.py +++ b/tests/unit/base/test_version.py @@ -1,5 +1,15 @@ +import unittest +from unittest.mock import Mock + +import aiounittest from tests import IntegrationTestCase from tests.holodeck import Request +from twilio.base.version import Version +from twilio.base.exceptions import ( + TwilioRestException, + TwilioServiceException, + TwilioException, +) from twilio.base.page import Page from twilio.http.response import Response @@ -89,3 +99,1141 @@ def test_fetch_redirect(self): response = self.client.messaging.v1.fetch(method="GET", uri="/Deactivations") self.assertIsNotNone(response) + + def test_delete_success(self): + self.holodeck.mock( + Response(201, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + + def test_delete_not_found(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_body(self): + """Test delete that returns JSON response body (V1 API style)""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + + def test_delete_no_content(self): + """Test traditional delete with no content (204)""" + self.holodeck.mock( + Response(204, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + + def test_delete_with_invalid_json(self): + """Test delete with response content that is not valid JSON""" + self.holodeck.mock( + Response(200, "Not valid JSON content"), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + + +class VersionExceptionTestCase(unittest.TestCase): + """Test cases for base Version.exception() method with RFC-9457 auto-detection""" + + def test_exception_rfc9457_auto_detection(self): + """Test that base Version auto-detects RFC-9457 errors and creates TwilioServiceException""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Invalid parameter", + "status": 400, + "code": 20001, + "detail": "The 'PhoneNumber' parameter is required.", + "instance": "/api/v1/accounts/AC123/calls/CA456" + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exception.title, "Invalid parameter") + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 20001) + self.assertEqual(exception.detail, "The 'PhoneNumber' parameter is required.") + self.assertEqual(exception.instance, "/api/v1/accounts/AC123/calls/CA456") + self.assertEqual(exception.method, "POST") + self.assertEqual(exception.uri, "/test") + + def test_exception_legacy_format_fallback(self): + """Test that base Version falls back to TwilioRestException for legacy errors""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "message": "Invalid phone number", + "code": 21211 + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 21211) + self.assertIn("Invalid phone number", exception.msg) + + def test_exception_rfc9457_with_validation_errors_base_version(self): + """Test base Version handles RFC-9457 with validation errors array""" + response = Mock(spec=Response) + response.status_code = 422 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Validation failed", + "status": 422, + "code": 20001, + "detail": "Request validation failed", + "errors": [ + {"detail": "must be a positive integer", "pointer": "#/age"}, + {"detail": "must be 'green', 'red' or 'blue'", "pointer": "#/profile/color"} + ] + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Validation error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.title, "Validation failed") + self.assertEqual(len(exception.errors), 2) + self.assertEqual(exception.errors[0]["detail"], "must be a positive integer") + self.assertEqual(exception.errors[0]["pointer"], "#/age") + + def test_exception_malformed_json_fallback(self): + """Test that base Version handles malformed JSON gracefully""" + response = Mock(spec=Response) + response.status_code = 500 + response.text = "This is not JSON" + + exception = Version.exception( + method="GET", uri="/test", response=response, message="Server error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 500) + + +class TwilioServiceExceptionTestCase(unittest.TestCase): + """Comprehensive test cases for TwilioServiceException""" + + def test_minimal_required_fields(self): + """Test TwilioServiceException with only required fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20003", + title="Authentication Failed", + status=401, + code=20003, + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20003") + self.assertEqual(exc.title, "Authentication Failed") + self.assertEqual(exc.status, 401) + self.assertEqual(exc.code, 20003) + self.assertIsNone(exc.detail) + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "GET") + self.assertEqual(exc.uri, "") + + def test_all_fields_populated(self): + """Test TwilioServiceException with all fields populated""" + errors = [ + {"detail": "Field is required", "pointer": "#/name"}, + {"detail": "Must be a valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Request", + status=400, + code=20001, + detail="The request could not be processed", + instance="/api/v1/accounts/AC123/messages/SM456", + errors=errors, + method="POST", + uri="/api/v1/messages", + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exc.title, "Invalid Request") + self.assertEqual(exc.status, 400) + self.assertEqual(exc.code, 20001) + self.assertEqual(exc.detail, "The request could not be processed") + self.assertEqual(exc.instance, "/api/v1/accounts/AC123/messages/SM456") + self.assertEqual(len(exc.errors), 2) + self.assertEqual(exc.errors[0]["detail"], "Field is required") + self.assertEqual(exc.errors[0]["pointer"], "#/name") + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/messages") + + def test_partial_optional_fields(self): + """Test TwilioServiceException with some optional fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20002", + title="Rate Limit Exceeded", + status=429, + code=20002, + detail="Too many requests", + method="POST", + uri="/api/v1/calls", + ) + + self.assertEqual(exc.detail, "Too many requests") + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/calls") + + def test_empty_errors_array(self): + """Test TwilioServiceException with explicitly empty errors array""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=[], + ) + + self.assertEqual(exc.errors, []) + + def test_none_errors_becomes_empty_list(self): + """Test that None errors parameter becomes empty list""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=None, + ) + + self.assertEqual(exc.errors, []) + self.assertIsInstance(exc.errors, list) + + def test_different_http_methods(self): + """Test TwilioServiceException with different HTTP methods""" + methods = ["GET", "POST", "PUT", "PATCH", "DELETE"] + + for method in methods: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method=method, + ) + self.assertEqual(exc.method, method) + + def test_different_status_codes(self): + """Test TwilioServiceException with various HTTP status codes""" + status_codes = [400, 401, 403, 404, 422, 429, 500, 502, 503] + + for status_code in status_codes: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=status_code, + code=20001, + ) + self.assertEqual(exc.status, status_code) + + def test_string_representation_non_tty(self): + """Test __str__ method for non-TTY output (plain text)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + ) + + # Mock sys.stderr to simulate non-TTY + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 400 error", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_non_tty_with_validation_errors(self): + """Test __str__ method for non-TTY with validation errors""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + detail="Request validation failed", + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 422 error", result) + self.assertIn("Validation Failed", result) + self.assertIn("Request validation failed", result) + self.assertIn("Validation errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty(self): + """Test __str__ method for TTY output (colored)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + instance="/api/v1/accounts/AC123/calls/CA456", + method="POST", + uri="/api/v1/calls", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + # Check for ANSI escape codes (color formatting) + self.assertIn("\033[", result) + # Check for content + self.assertIn("HTTP Error", result) + self.assertIn("POST /api/v1/calls", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + self.assertIn("400", result) + self.assertIn("20001", result) + self.assertIn("https://www.twilio.com/docs/api/errors/20001", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_with_validation_errors(self): + """Test __str__ method for TTY with validation errors (colored)""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + method="POST", + uri="/api/v1/users", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("Validation Errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + self.assertIn("#/email", result) + self.assertIn("must be valid", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_no_uri(self): + """Test __str__ method when uri is empty""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method="GET", + uri="", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("(no URI)", result) + finally: + sys.stderr = original_stderr + + def test_validation_errors_with_missing_fields(self): + """Test validation errors with missing detail or pointer fields""" + errors = [ + {"detail": "error detail"}, # missing pointer + {"pointer": "#/field"}, # missing detail + {}, # both missing + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + # Test non-TTY output + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + # Should handle missing fields gracefully + self.assertIn("Validation errors", result) + finally: + sys.stderr = original_stderr + + def test_multiple_validation_errors(self): + """Test with multiple validation errors""" + errors = [ + {"detail": "Field is required", "pointer": "#/firstName"}, + {"detail": "Must be at least 18", "pointer": "#/age"}, + {"detail": "Invalid format", "pointer": "#/phoneNumber"}, + {"detail": "Must be unique", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + self.assertEqual(len(exc.errors), 4) + self.assertEqual(exc.errors[2]["pointer"], "#/phoneNumber") + self.assertEqual(exc.errors[3]["detail"], "Must be unique") + + def test_exception_as_parent_class(self): + """Test that TwilioServiceException is a proper exception""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + ) + + self.assertIsInstance(exc, Exception) + self.assertIsInstance(exc, TwilioException) + + def test_exception_can_be_raised_and_caught(self): + """Test that TwilioServiceException can be raised and caught""" + with self.assertRaises(TwilioServiceException) as context: + raise TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Test Error", + status=400, + code=20001, + ) + + self.assertEqual(context.exception.title, "Test Error") + self.assertEqual(context.exception.code, 20001) + + +class ResponseInfoIntegrationTestCase(IntegrationTestCase): + """Integration tests for *_with_response_info methods""" + + def test_fetch_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + def test_update_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"name": "Updated Account"} + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + def test_delete_with_response_info(self): + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info(self): + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + def test_page_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = self.client.api.v2010.page_with_response_info( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + def test_fetch_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + def test_update_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + def test_delete_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_info_json_body(self): + """Test delete_with_response_info with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + def test_delete_with_response_info_no_content(self): + """Test delete_with_response_info with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_delete_with_response_info_invalid_json(self): + """Test delete_with_response_info with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + def test_fetch_with_response_info_empty_headers(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + def test_fetch_with_response_info_multiple_headers(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + def test_fetch_with_response_info_returns_tuple(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) + + +class AsyncVersionTestCase(aiounittest.AsyncTestCase): + def setUp(self): + from tests.holodeck import AsyncHolodeck + from twilio.rest import Client + + self.holodeck = AsyncHolodeck() + self.client = Client( + "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "AUTHTOKEN", http_client=self.holodeck + ) + + async def test_fetch_with_response_info_async(self): + """Test fetch_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + async def test_update_with_response_info_async(self): + """Test update_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.update_with_response_info_async( + method="POST", + uri="/Accounts/AC123.json", + data={"name": "Updated Account"}, + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + async def test_delete_with_response_info_async(self): + """Test delete_with_response_info_async method""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async(self): + """Test create_with_response_info_async method""" + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + async def test_page_with_response_info_async(self): + """Test page_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = ( + await self.client.api.v2010.page_with_response_info_async( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + async def test_fetch_with_response_info_async_error(self): + """Test fetch_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + async def test_update_with_response_info_async_error(self): + """Test update_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.update_with_response_info_async( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + async def test_delete_with_response_info_async_error(self): + """Test delete_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + async def test_delete_with_response_info_async_json_body(self): + """Test delete_with_response_info_async with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + async def test_delete_with_response_info_async_no_content(self): + """Test delete_with_response_info_async with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_delete_with_response_info_async_invalid_json(self): + """Test delete_with_response_info_async with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async_error(self): + """Test create_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + async def test_fetch_with_response_info_async_empty_headers(self): + """Test fetch_with_response_info_async with None headers""" + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + async def test_fetch_with_response_info_async_multiple_headers(self): + """Test fetch_with_response_info_async with multiple headers""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + async def test_fetch_with_response_info_async_returns_tuple(self): + """Test that fetch_with_response_info_async returns proper tuple structure""" + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) diff --git a/tests/unit/http/test_api_response.py b/tests/unit/http/test_api_response.py new file mode 100644 index 0000000000..4a1572b24c --- /dev/null +++ b/tests/unit/http/test_api_response.py @@ -0,0 +1,96 @@ +import unittest +from twilio.base.api_response import ApiResponse + + +class TestApiResponse(unittest.TestCase): + def test_initialization(self): + """Test ApiResponse initialization""" + data = {"sid": "AC123", "friendly_name": "Test"} + response = ApiResponse( + data=data, status_code=200, headers={"Content-Type": "application/json"} + ) + + self.assertEqual(response.data, data) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers["Content-Type"], "application/json") + + def test_repr(self): + """Test string representation""" + response = ApiResponse(data={"test": "data"}, status_code=201, headers={}) + repr_str = repr(response) + self.assertIn("201", repr_str) + self.assertIn("dict", repr_str) + + def test_str(self): + """Test human-readable string representation""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + str_repr = str(response) + self.assertIn("200", str_repr) + self.assertIn("dict", str_repr) + + def test_with_list_data(self): + """Test ApiResponse with list data""" + data = [{"sid": "AC1"}, {"sid": "AC2"}] + response = ApiResponse(data=data, status_code=200, headers={}) + self.assertEqual(len(response.data), 2) + self.assertEqual(response.status_code, 200) + + def test_with_boolean_data(self): + """Test ApiResponse with boolean data (delete operations)""" + response = ApiResponse(data=True, status_code=204, headers={}) + self.assertTrue(response.data) + self.assertEqual(response.status_code, 204) + + def test_with_different_status_codes(self): + """Test ApiResponse with various status codes""" + # Test 201 Created + response_201 = ApiResponse(data={"created": True}, status_code=201, headers={}) + self.assertEqual(response_201.status_code, 201) + + # Test 204 No Content + response_204 = ApiResponse(data=True, status_code=204, headers={}) + self.assertEqual(response_204.status_code, 204) + + # Test 200 OK + response_200 = ApiResponse(data={"ok": True}, status_code=200, headers={}) + self.assertEqual(response_200.status_code, 200) + + def test_headers_access(self): + """Test accessing various headers""" + headers = { + "Content-Type": "application/json", + "X-RateLimit-Remaining": "100", + "X-RateLimit-Limit": "1000", + } + response = ApiResponse(data={"test": "data"}, status_code=200, headers=headers) + + self.assertEqual(response.headers["Content-Type"], "application/json") + self.assertEqual(response.headers["X-RateLimit-Remaining"], "100") + self.assertEqual(response.headers["X-RateLimit-Limit"], "1000") + + def test_empty_headers(self): + """Test ApiResponse with empty headers""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + self.assertEqual(response.headers, {}) + + def test_data_attribute_types(self): + """Test that data attribute can hold various types""" + # Dictionary data + dict_response = ApiResponse(data={"key": "value"}, status_code=200, headers={}) + self.assertIsInstance(dict_response.data, dict) + + # List data + list_response = ApiResponse(data=[1, 2, 3], status_code=200, headers={}) + self.assertIsInstance(list_response.data, list) + + # Boolean data + bool_response = ApiResponse(data=True, status_code=204, headers={}) + self.assertIsInstance(bool_response.data, bool) + + # None data + none_response = ApiResponse(data=None, status_code=204, headers={}) + self.assertIsNone(none_response.data) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/http/test_async_http_client.py b/tests/unit/http/test_async_http_client.py index df43606843..23df35dc02 100644 --- a/tests/unit/http/test_async_http_client.py +++ b/tests/unit/http/test_async_http_client.py @@ -10,10 +10,11 @@ class MockResponse(object): A mock of the aiohttp.ClientResponse class """ - def __init__(self, text, status): + def __init__(self, text, status, method="GET"): self._text = text self.status = status self.headers = {} + self.method = method async def text(self): return self._text diff --git a/tests/unit/http/test_http_client.py b/tests/unit/http/test_http_client.py index 8484e57b17..9a74139d40 100644 --- a/tests/unit/http/test_http_client.py +++ b/tests/unit/http/test_http_client.py @@ -10,6 +10,7 @@ from twilio.base.version import Version from twilio.http.http_client import TwilioHttpClient from twilio.http.response import Response +from twilio.http.request import Request class TestHttpClientRequest(unittest.TestCase): @@ -293,6 +294,43 @@ def test_session_not_preserved(self): self.assertEqual(response_2.content, "response_2") +class TestTwilioRequest(unittest.TestCase): + def test_str(self): + + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + auth=("AC123", "token"), + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={"X-Custom-Header": "Value"}, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + def test_str_excludes_authorization_header(self): + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={ + "Authorization": "Bearer secret-token", + "X-Custom-Header": "Value", + }, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + class MyVersion(Version): def __init__(self, domain): super().__init__(domain, "v1") diff --git a/tests/unit/rest/test_client.py b/tests/unit/rest/test_client.py index 9623dc52ad..93338dfefa 100644 --- a/tests/unit/rest/test_client.py +++ b/tests/unit/rest/test_client.py @@ -1,7 +1,9 @@ import unittest + import aiounittest from mock import AsyncMock, Mock + from twilio.http.response import Response from twilio.rest import Client @@ -18,16 +20,16 @@ def test_set_client_edge_default_region(self): ) def test_set_client_region(self): - self.client.region = "region" + self.client.region = "us1" self.assertEqual( self.client.get_hostname("https://api.twilio.com"), - "https://api.region.twilio.com", + "https://api.us1.twilio.com", ) def test_set_uri_region(self): self.assertEqual( - self.client.get_hostname("https://api.region.twilio.com"), - "https://api.region.twilio.com", + self.client.get_hostname("https://api.us1.twilio.com"), + "https://api.us1.twilio.com", ) def test_set_client_edge_region(self): @@ -79,9 +81,19 @@ def test_periods_in_query(self): class TestUserAgentClients(unittest.TestCase): def setUp(self): self.client = Client("username", "password") + mock_response = Mock() + mock_response.status_code = 200 + mock_response.text = "" + mock_response.headers = {} + self.client.http_client.session = Mock() + self.client.http_client.session.prepare_request = Mock(side_effect=lambda r: r) + self.client.http_client.session.merge_environment_settings = Mock( + return_value={} + ) + self.client.http_client.session.send = Mock(return_value=mock_response) def tearDown(self): - self.client.http_client.session.close() + pass def test_set_default_user_agent(self): self.client.request("GET", "https://api.twilio.com/") diff --git a/twilio/__init__.py b/twilio/__init__.py index 8279b4dbd8..2ef30c7eb0 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,2 +1,2 @@ -__version_info__ = ("9", "4", "3") +__version_info__ = ("9", "11", "0") __version__ = ".".join(__version_info__) diff --git a/twilio/auth_strategy/token_auth_strategy.py b/twilio/auth_strategy/token_auth_strategy.py index ee51f05a43..33a8d385cb 100644 --- a/twilio/auth_strategy/token_auth_strategy.py +++ b/twilio/auth_strategy/token_auth_strategy.py @@ -1,7 +1,7 @@ import jwt import threading import logging -from datetime import datetime +from datetime import datetime, timezone from twilio.auth_strategy.auth_type import AuthType from twilio.auth_strategy.auth_strategy import AuthStrategy @@ -43,8 +43,10 @@ def is_token_expired(self, token): if exp is None: return True # No expiration time present, consider it expired - # Check if the expiration time has passed - return datetime.fromtimestamp(exp) < datetime.utcnow() + # Check if the expiration time has passed by using time-zone + return datetime.fromtimestamp(exp, tz=timezone.utc) < datetime.now( + timezone.utc + ) except jwt.DecodeError: return True # Token is invalid diff --git a/twilio/base/api_response.py b/twilio/base/api_response.py new file mode 100644 index 0000000000..4b6ea5969f --- /dev/null +++ b/twilio/base/api_response.py @@ -0,0 +1,51 @@ +""" +ApiResponse class for wrapping API responses with metadata +""" + +from typing import Dict, Generic, TypeVar + +T = TypeVar("T") + + +class ApiResponse(Generic[T]): + """ + Wrapper for API responses that includes HTTP metadata. + + This class is returned by *_with_http_info methods and provides access to: + - The response data (resource instance, list, or boolean) + - HTTP status code + - Response headers + + Attributes: + data: The response data (instance, list, or boolean for delete operations) + status_code: HTTP status code from the response + headers: Dictionary of response headers + + Example: + >>> response = client.accounts.create_with_http_info(friendly_name="Test") + >>> print(response.status_code) # 201 + >>> print(response.headers['Content-Type']) # application/json + >>> account = response.data + >>> print(account.sid) + """ + + def __init__(self, data: T, status_code: int, headers: Dict[str, str]): + """ + Initialize an ApiResponse + + Args: + data: The response payload (instance, list, or boolean) + status_code: HTTP status code (e.g., 200, 201, 204) + headers: Dictionary of response headers + """ + self.data = data + self.status_code = status_code + self.headers = headers + + def __repr__(self) -> str: + """String representation of the ApiResponse""" + return f"ApiResponse(status_code={self.status_code}, data={type(self.data).__name__})" + + def __str__(self) -> str: + """Human-readable string representation""" + return f"" diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py index b16f85bf5b..af5ccdb09c 100644 --- a/twilio/base/client_base.py +++ b/twilio/base/client_base.py @@ -34,7 +34,7 @@ def __init__( :param region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided :param http_client: HttpClient, defaults to TwilioHttpClient :param environment: Environment to look for auth details, defaults to os.environ - :param edge: Twilio Edge to make requests to, defaults to None + :param edge: Twilio Edge to make requests to, defaults to None. :param user_agent_extensions: Additions to the user agent string :param credential_provider: credential provider for authentication method that needs to be used """ diff --git a/twilio/base/exceptions.py b/twilio/base/exceptions.py index 8f3b7cc7a1..ad31cbe204 100644 --- a/twilio/base/exceptions.py +++ b/twilio/base/exceptions.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import sys -from typing import Optional +from typing import Optional, List, Dict class TwilioException(Exception): @@ -80,3 +80,140 @@ def get_uri(code: int) -> str: return msg else: return "HTTP {0} error: {1}".format(self.status, self.msg) + + +class TwilioServiceException(TwilioException): + """An RFC-9457 compliant exception from a Twilio service + + This exception follows the Problem Details for HTTP APIs specification + (RFC-9457). See https://www.rfc-editor.org/rfc/rfc9457.html + + :param str type: A URI reference that identifies the problem type + :param str title: A short, human-readable summary of the problem type + :param int status: The HTTP status code for this occurrence of the problem + :param int code: Twilio-specific error code + :param str|None detail: A human-readable explanation specific to this occurrence + :param str|None instance: A URI reference identifying the specific occurrence + :param list|None errors: Array of validation errors with detail and pointer fields + :param str method: The HTTP method used to make the request + :param str uri: The URI that caused the exception + """ + + def __init__( + self, + type_uri: str, + title: str, + status: int, + code: int, + detail: Optional[str] = None, + instance: Optional[str] = None, + errors: Optional[List[Dict[str, str]]] = None, + method: str = "GET", + uri: str = "", + ): + self.type = type_uri + self.title = title + self.status = status + self.code = code + self.detail = detail + self.instance = instance + self.errors = errors or [] + self.method = method + self.uri = uri + + def __str__(self) -> str: + """Pretty-print the exception for terminal output.""" + + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words + + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words + + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words + + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words + + def yellow(words: str) -> str: + return "\033[33m\033[49m%s\033[0m" % words + + # Check if we're in a TTY for colored output + if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): + msg_parts = [ + "\n{red_error} {request_was}\n\n{http_line}\n\n{twilio_returned}\n".format( + red_error=red("HTTP Error"), + request_was=white("Your request was:"), + http_line=( + teal("%s %s" % (self.method, self.uri)) + if self.uri + else teal("(no URI)") + ), + twilio_returned=white("Twilio returned the following information:"), + ) + ] + + # Title and detail + msg_parts.append( + "\n{title_label}: {title}\n".format( + title_label=white("Title"), + title=blue(self.title), + ) + ) + + if self.detail: + msg_parts.append( + "{detail_label}: {detail}\n".format( + detail_label=white("Detail"), + detail=blue(self.detail), + ) + ) + + # Code and status + msg_parts.append( + "{code_label}: {code} | {status_label}: {status}\n".format( + code_label=white("Error Code"), + code=blue(str(self.code)), + status_label=white("Status"), + status=blue(str(self.status)), + ) + ) + + # Validation errors if present + if self.errors: + msg_parts.append( + "\n{validation_label}:\n".format( + validation_label=white("Validation Errors"), + ) + ) + for error in self.errors: + msg_parts.append( + " {pointer}: {detail}\n".format( + pointer=yellow(error.get("pointer", "(unknown field)")), + detail=error.get("detail", "(no detail)"), + ) + ) + + # Documentation link + msg_parts.append( + "\n{more_info}\n\n{uri}\n\n".format( + more_info=white("More information may be available here:"), + uri=blue(self.type), + ) + ) + + return "".join(msg_parts) + else: + # Plain text output for non-TTY + msg = "HTTP {0} error: {1}".format(self.status, self.title) + if self.detail: + msg += " - {0}".format(self.detail) + if self.errors: + msg += " | Validation errors: {0}".format( + ", ".join( + "{0} ({1})".format(e.get("pointer", "?"), e.get("detail", "?")) + for e in self.errors + ) + ) + return msg diff --git a/twilio/base/token_pagination.py b/twilio/base/token_pagination.py new file mode 100644 index 0000000000..9631f7e14e --- /dev/null +++ b/twilio/base/token_pagination.py @@ -0,0 +1,154 @@ +from typing import Optional, Any, Dict + +from twilio.base.exceptions import TwilioException +from twilio.base.page import Page + + +class TokenPagination(Page): + """ + Represents a page of records using token-based pagination. + + Token-based pagination uses next_token and previous_token instead of + page numbers to navigate through results. + + Example expected response format with token metadata: + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "abc123", + "previousToken": "xyz789" + }, + "items": [ + { "id": 1, "name": "Item 1" }, + { "id": 2, "name": "Item 2" } + ] + } + """ + + def __init__( + self, + version, + response, + uri: str, + params: Optional[Dict[str, Any]] = None, + solution: Optional[Dict[str, Any]] = None, + ): + super().__init__(version, response, solution) + self._uri = uri + self._params = params if params is not None else {} + + @property + def key(self) -> Optional[str]: + """ + :return str: Returns the key that identifies the collection in the response. + """ + if "meta" in self._payload and "key" in self._payload["meta"]: + return self._payload["meta"]["key"] + return None + + @property + def page_size(self) -> Optional[int]: + """ + :return int: Returns the page size or None if doesn't exist. + """ + if "meta" in self._payload and "pageSize" in self._payload["meta"]: + return self._payload["meta"]["pageSize"] + return None + + @property + def next_token(self) -> Optional[str]: + """ + :return str: Returns the next_token for pagination or None if doesn't exist. + """ + if "meta" in self._payload and "nextToken" in self._payload["meta"]: + return self._payload["meta"]["nextToken"] + return None + + @property + def previous_token(self) -> Optional[str]: + """ + :return str: Returns the previous_token for pagination or None if doesn't exist. + """ + if "meta" in self._payload and "previousToken" in self._payload["meta"]: + return self._payload["meta"]["previousToken"] + return None + + def _get_page(self, token: Optional[str]) -> Optional["TokenPagination"]: + """ + Internal helper to fetch a page using a given token. + + :param token: The pagination token to use. + :return: The page or None if no token exists. + """ + if not token: + return None + + if not self._uri: + raise TwilioException("URI must be provided for token pagination") + + self._params["pageToken"] = token + + response = self._version.page(method="GET", uri=self._uri, params=self._params) + cls = type(self) + return cls(self._version, response, self._uri, self._params, self._solution) + + async def _get_page_async( + self, token: Optional[str] + ) -> Optional["TokenPagination"]: + """ + Internal async helper to fetch a page using a given token. + + :param token: The pagination token to use. + :return: The page or None if no token exists. + """ + if not token: + return None + + if not self._uri: + raise TwilioException("URI must be provided for token pagination") + + # Construct full URL with pageToken parameter + self._params["pageToken"] = token + response = self._version.page(method="GET", uri=self._uri, params=self._params) + cls = type(self) + return cls(self._version, response, self._uri, self._params, self._solution) + + def next_page(self) -> Optional["TokenPagination"]: + """ + Return the next page using token-based pagination. + Makes a request to the same URI with pageToken set to nextToken. + + :return: The next page or None if no next token exists. + """ + return self._get_page(self.next_token) + + async def next_page_async(self) -> Optional["TokenPagination"]: + """ + Asynchronously return the next page using token-based pagination. + Makes a request to the same URI with pageToken set to nextToken. + + :return: The next page or None if no next token exists. + """ + return await self._get_page_async(self.next_token) + + def previous_page(self) -> Optional["TokenPagination"]: + """ + Return the previous page using token-based pagination. + Makes a request to the same URI with pageToken set to previousToken. + + :return: The previous page or None if no previous token exists. + """ + return self._get_page(self.previous_token) + + async def previous_page_async(self) -> Optional["TokenPagination"]: + """ + Asynchronously return the previous page using token-based pagination. + Makes a request to the same URI with pageToken set to previousToken. + + :return: The previous page or None if no previous token exists. + """ + return await self._get_page_async(self.previous_token) + + def __repr__(self) -> str: + return "" diff --git a/twilio/base/version.py b/twilio/base/version.py index ed7e86f499..f6654a86cc 100644 --- a/twilio/base/version.py +++ b/twilio/base/version.py @@ -1,9 +1,9 @@ import json -from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple +from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple, Union from twilio.base import values from twilio.base.domain import Domain -from twilio.base.exceptions import TwilioRestException +from twilio.base.exceptions import TwilioRestException, TwilioServiceException from twilio.base.page import Page from twilio.http.response import Response @@ -84,20 +84,41 @@ async def request_async( @classmethod def exception( cls, method: str, uri: str, response: Response, message: str - ) -> TwilioRestException: + ) -> Union[TwilioRestException, TwilioServiceException]: """ - Wraps an exceptional response in a `TwilioRestException`. + Wraps an exceptional response in a `TwilioRestException` or `TwilioServiceException`. + + If the response is RFC-9457 compliant (contains 'type', 'title', 'status', and 'code' fields), + returns a TwilioServiceException. Otherwise, returns a TwilioRestException for backward compatibility. """ # noinspection PyBroadException try: error_payload = json.loads(response.text) - if "message" in error_payload: - message = "{}: {}".format(message, error_payload["message"]) - details = error_payload.get("details") - code = error_payload.get("code", response.status_code) - return TwilioRestException( - response.status_code, uri, message, code, method, details - ) + + # Check if this is an RFC-9457 compliant error response + # Required fields: type, title, status, code + if all(key in error_payload for key in ["type", "title", "status", "code"]): + # This is an RFC-9457 compliant error response + return TwilioServiceException( + type_uri=error_payload["type"], + title=error_payload["title"], + status=error_payload["status"], + code=error_payload["code"], + detail=error_payload.get("detail"), + instance=error_payload.get("instance"), + errors=error_payload.get("errors"), + method=method, + uri=uri, + ) + else: + # Legacy error format - use TwilioRestException + if "message" in error_payload: + message = "{}: {}".format(message, error_payload["message"]) + details = error_payload.get("details") + code = error_payload.get("code", response.status_code) + return TwilioRestException( + response.status_code, uri, message, code, method, details + ) except Exception: return TwilioRestException( response.status_code, uri, message, response.status_code, method @@ -166,6 +187,72 @@ async def fetch_async( ) return self._parse_fetch(method, uri, response) + def fetch_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Fetch a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_fetch(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def fetch_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Asynchronously fetch a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_fetch(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + def _parse_update(self, method: str, uri: str, response: Response) -> Any: """ Parses update response JSON @@ -229,14 +316,138 @@ async def update_async( return self._parse_update(method, uri, response) - def _parse_delete(self, method: str, uri: str, response: Response) -> bool: + def update_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Update a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_update(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def update_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: """ - Parses delete response JSON + Asynchronously update a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (typically 200) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_update(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + def patch_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + return self.update_with_response_info( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def patch_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + return await self.update_with_response_info_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def _parse_delete(self, method: str, uri: str, response: Response) -> Any: + """ + Parses delete response. Returns response body as dict if present, otherwise True. + + For V1 APIs that return response bodies on delete (e.g., 202 with JSON), + this returns the parsed JSON payload. For traditional deletes (e.g., 204 No Content), + this returns True for backward compatibility. """ if response.status_code < 200 or response.status_code >= 300: raise self.exception(method, uri, response, "Unable to delete record") - return response.status_code == 204 + # If response has content, parse and return it (V1 delete with response body) + if response.content and response.text: + try: + return json.loads(response.text) + except (ValueError, json.JSONDecodeError): + # If JSON parsing fails, fall back to boolean + pass + + return ( + True # Traditional delete: if response code is 2XX, deletion was successful + ) def delete( self, @@ -292,6 +503,74 @@ async def delete_async( return self._parse_delete(method, uri, response) + def delete_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Union[Dict[str, Any], bool], int, Dict[str, str]]: + """ + Delete a resource and return response metadata + + Returns: + tuple: (payload_or_success, status_code, headers_dict) + - payload_or_success: Response body dict if present (V1 APIs with response body), + or True boolean for traditional deletes (204 No Content) + - status_code: HTTP status code (typically 202 or 204 for successful delete) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + result = self._parse_delete(method, uri, response) + return result, response.status_code, dict(response.headers or {}) + + async def delete_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Union[Dict[str, Any], bool], int, Dict[str, str]]: + """ + Asynchronously delete a resource and return response metadata + + Returns: + tuple: (payload_or_success, status_code, headers_dict) + - payload_or_success: Response body dict if present (V1 APIs with response body), + or True boolean for traditional deletes (204 No Content) + - status_code: HTTP status code (typically 202 or 204 for successful delete) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + result = self._parse_delete(method, uri, response) + return result, response.status_code, dict(response.headers or {}) + def read_limits( self, limit: Optional[int] = None, page_size: Optional[int] = None ) -> Dict[str, object]: @@ -361,6 +640,70 @@ async def page_async( allow_redirects=allow_redirects, ) + def page_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Response, int, Dict[str, str]]: + """ + Fetch a page and return response metadata + + Returns: + tuple: (response_object, status_code, headers_dict) + - response_object: The Response object (not parsed JSON) + - status_code: HTTP status code + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return response, response.status_code, dict(response.headers or {}) + + async def page_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Response, int, Dict[str, str]]: + """ + Asynchronously fetch a page and return response metadata + + Returns: + tuple: (response_object, status_code, headers_dict) + - response_object: The Response object (not parsed JSON) + - status_code: HTTP status code + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return response, response.status_code, dict(response.headers or {}) + def stream( self, page: Optional[Page], @@ -434,6 +777,9 @@ def _parse_create(self, method: str, uri: str, response: Response) -> Any: if response.status_code < 200 or response.status_code >= 300: raise self.exception(method, uri, response, "Unable to create record") + if not response.text: + return {} + return json.loads(response.text) def create( @@ -487,3 +833,69 @@ async def create_async( allow_redirects=allow_redirects, ) return self._parse_create(method, uri, response) + + def create_with_response_info( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Create a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (e.g., 201) + - headers_dict: Response headers as a dictionary + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_create(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) + + async def create_with_response_info_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Tuple[Any, int, Dict[str, str]]: + """ + Asynchronously create a resource and return response metadata + + Returns: + tuple: (payload_dict, status_code, headers_dict) + - payload_dict: The JSON response body as a dictionary + - status_code: HTTP status code (e.g., 201) + - headers_dict: Response headers as a dictionary + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + payload = self._parse_create(method, uri, response) + return payload, response.status_code, dict(response.headers or {}) diff --git a/twilio/http/client_token_manager.py b/twilio/http/client_token_manager.py index d65acb2ba2..cec693ed06 100644 --- a/twilio/http/client_token_manager.py +++ b/twilio/http/client_token_manager.py @@ -29,7 +29,7 @@ def __init__( self.client = Client() def fetch_access_token(self): - token_instance = self.client.preview_iam.v1.token.create( + token_instance = self.client.oauth.v2.token.create( grant_type=self.grant_type, client_id=self.client_id, client_secret=self.client_secret, diff --git a/twilio/http/http_client.py b/twilio/http/http_client.py index e15be86354..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -40,7 +40,7 @@ def __init__( self.session = Session() if pool_connections else None if self.session and max_retries is not None: self.session.mount("https://", HTTPAdapter(max_retries=max_retries)) - if self.session is not None: + elif self.session is not None: self.session.mount( "https://", HTTPAdapter(pool_maxsize=min(32, os.cpu_count() + 4)) ) diff --git a/twilio/http/orgs_token_manager.py b/twilio/http/orgs_token_manager.py index 767ed270af..c5e406ffd3 100644 --- a/twilio/http/orgs_token_manager.py +++ b/twilio/http/orgs_token_manager.py @@ -29,7 +29,7 @@ def __init__( self.client = Client() def fetch_access_token(self): - token_instance = self.client.preview_iam.v1.token.create( + token_instance = self.client.oauth.v2.token.create( grant_type=self.grant_type, client_id=self.client_id, client_secret=self.client_secret, diff --git a/twilio/http/request.py b/twilio/http/request.py index e75cf12b0d..4aef7017bd 100644 --- a/twilio/http/request.py +++ b/twilio/http/request.py @@ -56,10 +56,6 @@ def __eq__(self, other) -> bool: ) def __str__(self) -> str: - auth = "" - if self.auth and self.auth != Match.ANY: - auth = "{} ".format(self.auth) - params = "" if self.params and self.params != Match.ANY: params = "?{}".format(urlencode(self.params, doseq=True)) @@ -75,11 +71,14 @@ def __str__(self) -> str: headers = "" if self.headers and self.headers != Match.ANY: headers = "\n{}".format( - "\n".join(' -H "{}: {}"'.format(k, v) for k, v in self.headers.items()) + "\n".join( + ' -H "{}: {}"'.format(k, v) + for k, v in self.headers.items() + if k.lower() != "authorization" + ) ) - return "{auth}{method} {url}{params}{data}{headers}".format( - auth=auth, + return "{method} {url}{params}{data}{headers}".format( method=self.method, url=self.url, params=params, diff --git a/twilio/http/validation_client.py b/twilio/http/validation_client.py index 1a4a83f0a5..4a376c7f4f 100644 --- a/twilio/http/validation_client.py +++ b/twilio/http/validation_client.py @@ -8,7 +8,6 @@ from twilio.http.response import Response from twilio.jwt.validation import ClientValidationJwt - ValidationPayload = namedtuple( "ValidationPayload", ["method", "path", "query_string", "all_headers", "signed_headers", "body"], diff --git a/twilio/jwt/__init__.py b/twilio/jwt/__init__.py index 7a51ea70d5..c17b548516 100644 --- a/twilio/jwt/__init__.py +++ b/twilio/jwt/__init__.py @@ -1,7 +1,6 @@ import jwt as jwt_lib import time - __all__ = ["Jwt", "JwtDecodeError"] diff --git a/twilio/rest/__init__.py b/twilio/rest/__init__.py index 5838363c52..fe422a931b 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -16,7 +16,6 @@ if TYPE_CHECKING: from twilio.rest.accounts import Accounts from twilio.rest.api import Api - from twilio.rest.assistants import Assistants from twilio.rest.bulkexports import Bulkexports from twilio.rest.chat import Chat from twilio.rest.content import Content @@ -29,10 +28,11 @@ from twilio.rest.insights import Insights from twilio.rest.intelligence import Intelligence from twilio.rest.ip_messaging import IpMessaging + from twilio.rest.knowledge import Knowledge from twilio.rest.lookups import Lookups from twilio.rest.marketplace import Marketplace + from twilio.rest.memory import Memory from twilio.rest.messaging import Messaging - from twilio.rest.microvisor import Microvisor from twilio.rest.monitor import Monitor from twilio.rest.notify import Notify from twilio.rest.numbers import Numbers @@ -129,7 +129,6 @@ def __init__( # Domains self._accounts: Optional["Accounts"] = None self._api: Optional["Api"] = None - self._assistants: Optional["Assistants"] = None self._bulkexports: Optional["Bulkexports"] = None self._chat: Optional["Chat"] = None self._content: Optional["Content"] = None @@ -142,10 +141,11 @@ def __init__( self._insights: Optional["Insights"] = None self._intelligence: Optional["Intelligence"] = None self._ip_messaging: Optional["IpMessaging"] = None + self._knowledge: Optional["Knowledge"] = None self._lookups: Optional["Lookups"] = None self._marketplace: Optional["Marketplace"] = None + self._memory: Optional["Memory"] = None self._messaging: Optional["Messaging"] = None - self._microvisor: Optional["Microvisor"] = None self._monitor: Optional["Monitor"] = None self._notify: Optional["Notify"] = None self._numbers: Optional["Numbers"] = None @@ -192,19 +192,6 @@ def api(self) -> "Api": self._api = Api(self) return self._api - @property - def assistants(self) -> "Assistants": - """ - Access the Assistants Twilio Domain - - :returns: Assistants Twilio Domain - """ - if self._assistants is None: - from twilio.rest.assistants import Assistants - - self._assistants = Assistants(self) - return self._assistants - @property def bulkexports(self) -> "Bulkexports": """ @@ -361,6 +348,19 @@ def ip_messaging(self) -> "IpMessaging": self._ip_messaging = IpMessaging(self) return self._ip_messaging + @property + def knowledge(self) -> "Knowledge": + """ + Access the Knowledge Twilio Domain + + :returns: Knowledge Twilio Domain + """ + if self._knowledge is None: + from twilio.rest.knowledge import Knowledge + + self._knowledge = Knowledge(self) + return self._knowledge + @property def lookups(self) -> "Lookups": """ @@ -387,6 +387,19 @@ def marketplace(self) -> "Marketplace": self._marketplace = Marketplace(self) return self._marketplace + @property + def memory(self) -> "Memory": + """ + Access the Memory Twilio Domain + + :returns: Memory Twilio Domain + """ + if self._memory is None: + from twilio.rest.memory import Memory + + self._memory = Memory(self) + return self._memory + @property def messaging(self) -> "Messaging": """ @@ -400,19 +413,6 @@ def messaging(self) -> "Messaging": self._messaging = Messaging(self) return self._messaging - @property - def microvisor(self) -> "Microvisor": - """ - Access the Microvisor Twilio Domain - - :returns: Microvisor Twilio Domain - """ - if self._microvisor is None: - from twilio.rest.microvisor import Microvisor - - self._microvisor = Microvisor(self) - return self._microvisor - @property def monitor(self) -> "Monitor": """ diff --git a/twilio/rest/accounts/v1/__init__.py b/twilio/rest/accounts/v1/__init__.py index 6f5012d0fa..8be121c71e 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -19,6 +19,7 @@ from twilio.rest.accounts.v1.bulk_consents import BulkConsentsList from twilio.rest.accounts.v1.bulk_contacts import BulkContactsList from twilio.rest.accounts.v1.credential import CredentialList +from twilio.rest.accounts.v1.messaging_geopermissions import MessagingGeopermissionsList from twilio.rest.accounts.v1.safelist import SafelistList from twilio.rest.accounts.v1.secondary_auth_token import SecondaryAuthTokenList @@ -36,6 +37,7 @@ def __init__(self, domain: Domain): self._bulk_consents: Optional[BulkConsentsList] = None self._bulk_contacts: Optional[BulkContactsList] = None self._credentials: Optional[CredentialList] = None + self._messaging_geopermissions: Optional[MessagingGeopermissionsList] = None self._safelist: Optional[SafelistList] = None self._secondary_auth_token: Optional[SecondaryAuthTokenList] = None @@ -63,6 +65,12 @@ def credentials(self) -> CredentialList: self._credentials = CredentialList(self) return self._credentials + @property + def messaging_geopermissions(self) -> MessagingGeopermissionsList: + if self._messaging_geopermissions is None: + self._messaging_geopermissions = MessagingGeopermissionsList(self) + return self._messaging_geopermissions + @property def safelist(self) -> SafelistList: if self._safelist is None: diff --git a/twilio/rest/accounts/v1/auth_token_promotion.py b/twilio/rest/accounts/v1/auth_token_promotion.py index 8580538a9b..e8679fd724 100644 --- a/twilio/rest/accounts/v1/auth_token_promotion.py +++ b/twilio/rest/accounts/v1/auth_token_promotion.py @@ -13,8 +13,9 @@ """ from datetime import datetime -from typing import Any, Dict, Optional -from twilio.base import deserialize, values +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -59,23 +60,61 @@ def _proxy(self) -> "AuthTokenPromotionContext": ) return self._context - def update(self) -> "AuthTokenPromotionInstance": + def update( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> "AuthTokenPromotionInstance": """ Update the AuthTokenPromotionInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The updated AuthTokenPromotionInstance """ - return self._proxy.update() + return self._proxy.update( + suppress_email_notification=suppress_email_notification, + ) - async def update_async(self) -> "AuthTokenPromotionInstance": + async def update_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> "AuthTokenPromotionInstance": """ Asynchronous coroutine to update the AuthTokenPromotionInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The updated AuthTokenPromotionInstance """ - return await self._proxy.update_async() + return await self._proxy.update_async( + suppress_email_notification=suppress_email_notification, + ) + + def update_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the AuthTokenPromotionInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + suppress_email_notification=suppress_email_notification, + ) + + async def update_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + suppress_email_notification=suppress_email_notification, + ) def __repr__(self) -> str: """ @@ -99,44 +138,122 @@ def __init__(self, version: Version): self._uri = "/AuthTokens/Promote" - def update(self) -> AuthTokenPromotionInstance: + def _update( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: """ - Update the AuthTokenPromotionInstance + Internal helper for update operation - - :returns: The updated AuthTokenPromotionInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({}) + data = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) headers = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> AuthTokenPromotionInstance: + """ + Update the AuthTokenPromotionInstance + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: The updated AuthTokenPromotionInstance + """ + payload, _, _ = self._update( + suppress_email_notification=suppress_email_notification + ) return AuthTokenPromotionInstance(self._version, payload) - async def update_async(self) -> AuthTokenPromotionInstance: + def update_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: """ - Asynchronous coroutine to update the AuthTokenPromotionInstance + Update the AuthTokenPromotionInstance and return response metadata + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. - :returns: The updated AuthTokenPromotionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + suppress_email_notification=suppress_email_notification + ) + instance = AuthTokenPromotionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of({}) + data = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) headers = values.of({}) + headers["Content-Type"] = "application/x-www-form-urlencoded" + headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> AuthTokenPromotionInstance: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: The updated AuthTokenPromotionInstance + """ + payload, _, _ = await self._update_async( + suppress_email_notification=suppress_email_notification + ) return AuthTokenPromotionInstance(self._version, payload) + async def update_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance and return response metadata + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + suppress_email_notification=suppress_email_notification + ) + instance = AuthTokenPromotionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/accounts/v1/bulk_consents.py b/twilio/rest/accounts/v1/bulk_consents.py index 3e4564386b..423b8ed7eb 100644 --- a/twilio/rest/accounts/v1/bulk_consents.py +++ b/twilio/rest/accounts/v1/bulk_consents.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,13 +54,12 @@ def __init__(self, version: Version): self._uri = "/Consents/Bulk" - def create(self, items: List[object]) -> BulkConsentsInstance: + def _create(self, items: List[object]) -> tuple: """ - Create the BulkConsentsInstance + Internal helper for create operation - :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; and `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]. - - :returns: The created BulkConsentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -73,19 +73,39 @@ def create(self, items: List[object]) -> BulkConsentsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, items: List[object]) -> BulkConsentsInstance: + """ + Create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + payload, _, _ = self._create(items=items) return BulkConsentsInstance(self._version, payload) - async def create_async(self, items: List[object]) -> BulkConsentsInstance: + def create_with_http_info(self, items: List[object]) -> ApiResponse: """ - Asynchronously create the BulkConsentsInstance + Create the BulkConsentsInstance and return response metadata - :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; and `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]. + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. - :returns: The created BulkConsentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(items=items) + instance = BulkConsentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, items: List[object]) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -99,12 +119,33 @@ async def create_async(self, items: List[object]) -> BulkConsentsInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, items: List[object]) -> BulkConsentsInstance: + """ + Asynchronously create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + payload, _, _ = await self._create_async(items=items) return BulkConsentsInstance(self._version, payload) + async def create_with_http_info_async(self, items: List[object]) -> ApiResponse: + """ + Asynchronously create the BulkConsentsInstance and return response metadata + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(items=items) + instance = BulkConsentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/accounts/v1/bulk_contacts.py b/twilio/rest/accounts/v1/bulk_contacts.py index 17b6da33f3..4ede446a9e 100644 --- a/twilio/rest/accounts/v1/bulk_contacts.py +++ b/twilio/rest/accounts/v1/bulk_contacts.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,13 +54,12 @@ def __init__(self, version: Version): self._uri = "/Contacts/Bulk" - def create(self, items: List[object]) -> BulkContactsInstance: + def _create(self, items: List[object]) -> tuple: """ - Create the BulkContactsInstance + Internal helper for create operation - :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. - - :returns: The created BulkContactsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -73,19 +73,39 @@ def create(self, items: List[object]) -> BulkContactsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, items: List[object]) -> BulkContactsInstance: + """ + Create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + payload, _, _ = self._create(items=items) return BulkContactsInstance(self._version, payload) - async def create_async(self, items: List[object]) -> BulkContactsInstance: + def create_with_http_info(self, items: List[object]) -> ApiResponse: """ - Asynchronously create the BulkContactsInstance + Create the BulkContactsInstance and return response metadata :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. - :returns: The created BulkContactsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(items=items) + instance = BulkContactsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, items: List[object]) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -99,12 +119,33 @@ async def create_async(self, items: List[object]) -> BulkContactsInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, items: List[object]) -> BulkContactsInstance: + """ + Asynchronously create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + payload, _, _ = await self._create_async(items=items) return BulkContactsInstance(self._version, payload) + async def create_with_http_info_async(self, items: List[object]) -> ApiResponse: + """ + Asynchronously create the BulkContactsInstance and return response metadata + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(items=items) + instance = BulkContactsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/accounts/v1/credential/aws.py b/twilio/rest/accounts/v1/credential/aws.py index ba5335accd..0c81106aec 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AwsContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AwsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AwsInstance": """ Fetch the AwsInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "AwsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AwsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AwsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": """ Update the AwsInstance @@ -130,6 +168,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the AwsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -157,6 +223,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/AWS/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AwsInstance @@ -164,10 +244,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AwsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -176,62 +278,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AwsInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AwsInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AwsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AwsInstance: + """ + Fetch the AwsInstance + + :returns: The fetched AwsInstance + """ + payload, _, _ = self._fetch() return AwsInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AwsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AwsInstance + Fetch the AwsInstance and return response metadata - :returns: The fetched AwsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AwsInstance: + """ + Asynchronous coroutine to fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + payload, _, _ = await self._fetch_async() return AwsInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the AwsInstance + Asynchronous coroutine to fetch the AwsInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated AwsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -245,21 +400,43 @@ def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstanc headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: + """ + Update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return AwsInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> AwsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AwsInstance + Update the AwsInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated AwsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -273,12 +450,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AwsInstance: + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return AwsInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -297,6 +501,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: :param payload: Payload response from the API """ + return AwsInstance(self._version, payload) def __repr__(self) -> str: @@ -321,20 +526,17 @@ def __init__(self, version: Version): self._uri = "/Credentials/AWS" - def create( + def _create( self, credentials: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> AwsInstance: + ) -> tuple: """ - Create the AwsInstance - - :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + Internal helper for create operation - :returns: The created AwsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -350,20 +552,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AwsInstance(self._version, payload) - - async def create_async( + def create( self, credentials: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, ) -> AwsInstance: """ - Asynchronously create the AwsInstance + Create the AwsInstance :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -371,6 +571,48 @@ async def create_async( :returns: The created AwsInstance """ + payload, _, _ = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + return AwsInstance(self._version, payload) + + def create_with_http_info( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AwsInstance and return response metadata + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -385,12 +627,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Asynchronously create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + payload, _, _ = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) return AwsInstance(self._version, payload) + async def create_with_http_info_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AwsInstance and return response metadata + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -441,6 +726,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -460,6 +795,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -486,6 +822,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -494,6 +831,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AwsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -560,6 +947,76 @@ async def page_async( ) return AwsPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AwsPage: """ Retrieve a specific page of AwsInstance records from the API. diff --git a/twilio/rest/accounts/v1/credential/public_key.py b/twilio/rest/accounts/v1/credential/public_key.py index c2b4f9bbee..1e5333fe17 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PublicKeyContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PublicKeyInstance": """ Fetch the PublicKeyInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "PublicKeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "PublicKeyInstance": @@ -132,6 +170,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PublicKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PublicKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +225,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PublicKeyInstance @@ -166,10 +246,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PublicKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -178,64 +280,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PublicKeyInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PublicKeyInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PublicKeyInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublicKeyInstance: + """ + Fetch the PublicKeyInstance + + :returns: The fetched PublicKeyInstance + """ + payload, _, _ = self._fetch() return PublicKeyInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> PublicKeyInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PublicKeyInstance + Fetch the PublicKeyInstance and return response metadata - :returns: The fetched PublicKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PublicKeyInstance: + """ + Asynchronous coroutine to fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + payload, _, _ = await self._fetch_async() return PublicKeyInstance( self._version, payload, sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> PublicKeyInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the PublicKeyInstance + Asynchronous coroutine to fetch the PublicKeyInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated PublicKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -249,22 +402,46 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset ) -> PublicKeyInstance: """ - Asynchronous coroutine to update the PublicKeyInstance + Update the PublicKeyInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :returns: The updated PublicKeyInstance """ + payload, _, _ = self._update(friendly_name=friendly_name) + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PublicKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -277,12 +454,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PublicKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -301,6 +505,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: :param payload: Payload response from the API """ + return PublicKeyInstance(self._version, payload) def __repr__(self) -> str: @@ -325,20 +530,17 @@ def __init__(self, version: Version): self._uri = "/Credentials/PublicKeys" - def create( + def _create( self, public_key: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> PublicKeyInstance: + ) -> tuple: """ - Create the PublicKeyInstance - - :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + Internal helper for create operation - :returns: The created PublicKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -354,20 +556,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PublicKeyInstance(self._version, payload) - - async def create_async( + def create( self, public_key: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, ) -> PublicKeyInstance: """ - Asynchronously create the PublicKeyInstance + Create the PublicKeyInstance :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -375,6 +575,44 @@ async def create_async( :returns: The created PublicKeyInstance """ + payload, _, _ = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + return PublicKeyInstance(self._version, payload) + + def create_with_http_info( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PublicKeyInstance and return response metadata + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -389,12 +627,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Asynchronously create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + payload, _, _ = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) return PublicKeyInstance(self._version, payload) + async def create_with_http_info_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PublicKeyInstance and return response metadata + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -445,6 +722,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -464,6 +791,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -490,6 +818,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -498,6 +827,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PublicKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -564,6 +943,76 @@ async def page_async( ) return PublicKeyPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublicKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PublicKeyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublicKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PublicKeyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PublicKeyPage: """ Retrieve a specific page of PublicKeyInstance records from the API. diff --git a/twilio/rest/accounts/v1/messaging_geopermissions.py b/twilio/rest/accounts/v1/messaging_geopermissions.py new file mode 100644 index 0000000000..0d077f885b --- /dev/null +++ b/twilio/rest/accounts/v1/messaging_geopermissions.py @@ -0,0 +1,261 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MessagingGeopermissionsInstance(InstanceResource): + """ + :ivar permissions: A list of objects where each object represents the result of processing a messaging Geo Permission. Each object contains the following fields: `country_code`, the country code of the country for which the permission was updated; `type`, the type of the permission i.e. country; `enabled`, true if the permission is enabled else false; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.permissions: Optional[Dict[str, object]] = payload.get("permissions") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class MessagingGeopermissionsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MessagingGeopermissionsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging/GeoPermissions" + + def _fetch(self, country_code: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "CountryCode": country_code, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, country_code: Union[str, object] = values.unset + ) -> MessagingGeopermissionsInstance: + """ + Fetch the MessagingGeopermissionsInstance + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: The fetched MessagingGeopermissionsInstance + """ + payload, _, _ = self._fetch(country_code=country_code) + return MessagingGeopermissionsInstance(self._version, payload) + + def fetch_with_http_info( + self, country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MessagingGeopermissionsInstance and return response metadata + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(country_code=country_code) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, country_code: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "CountryCode": country_code, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, country_code: Union[str, object] = values.unset + ) -> MessagingGeopermissionsInstance: + """ + Asynchronously fetch the MessagingGeopermissionsInstance + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: The fetched MessagingGeopermissionsInstance + """ + payload, _, _ = await self._fetch_async(country_code=country_code) + return MessagingGeopermissionsInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the MessagingGeopermissionsInstance and return response metadata + + :param country_code: The country code to filter the geo permissions. If provided, only the geo permission for the specified country will be returned. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + country_code=country_code + ) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permissions: List[object]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permissions": serialize.map( + permissions, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def update(self, permissions: List[object]) -> MessagingGeopermissionsInstance: + """ + Update the MessagingGeopermissionsInstance + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: The updated MessagingGeopermissionsInstance + """ + payload, _, _ = self._update(permissions=permissions) + return MessagingGeopermissionsInstance(self._version, payload) + + def update_with_http_info(self, permissions: List[object]) -> ApiResponse: + """ + Update the MessagingGeopermissionsInstance and return response metadata + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permissions=permissions) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permissions: List[object]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Permissions": serialize.map( + permissions, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, permissions: List[object] + ) -> MessagingGeopermissionsInstance: + """ + Asynchronously update the MessagingGeopermissionsInstance + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: The updated MessagingGeopermissionsInstance + """ + payload, _, _ = await self._update_async(permissions=permissions) + return MessagingGeopermissionsInstance(self._version, payload) + + async def update_with_http_info_async( + self, permissions: List[object] + ) -> ApiResponse: + """ + Asynchronously update the MessagingGeopermissionsInstance and return response metadata + + :param permissions: A list of objects where each object represents the Geo Permission to be updated. Each object contains the following fields: `country_code`, unique code for each country of Geo Permission; `type`, permission type of the Geo Permission i.e. country; `enabled`, configure true for enabling the Geo Permission, false for disabling the Geo Permission. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + permissions=permissions + ) + instance = MessagingGeopermissionsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/accounts/v1/safelist.py b/twilio/rest/accounts/v1/safelist.py index 0bbbb32420..f7e7912dde 100644 --- a/twilio/rest/accounts/v1/safelist.py +++ b/twilio/rest/accounts/v1/safelist.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +24,7 @@ class SafelistInstance(InstanceResource): """ :ivar sid: The unique string that we created to identify the SafeList resource. - :ivar phone_number: The phone number in SafeList. + :ivar phone_number: The phone number or phone number 1k prefix in SafeList. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -55,13 +56,12 @@ def __init__(self, version: Version): self._uri = "/SafeList/Numbers" - def create(self, phone_number: str) -> SafelistInstance: + def _create(self, phone_number: str) -> tuple: """ - Create the SafelistInstance + Internal helper for create operation - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - - :returns: The created SafelistInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -75,19 +75,39 @@ def create(self, phone_number: str) -> SafelistInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + payload, _, _ = self._create(phone_number=phone_number) return SafelistInstance(self._version, payload) - async def create_async(self, phone_number: str) -> SafelistInstance: + def create_with_http_info(self, phone_number: str) -> ApiResponse: """ - Asynchronously create the SafelistInstance + Create the SafelistInstance and return response metadata - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :returns: The created SafelistInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -101,18 +121,41 @@ async def create_async(self, phone_number: str) -> SafelistInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + payload, _, _ = await self._create_async(phone_number=phone_number) return SafelistInstance(self._version, payload) - def delete(self, phone_number: Union[str, object] = values.unset) -> bool: + async def create_with_http_info_async(self, phone_number: str) -> ApiResponse: """ - Asynchronously delete the SafelistInstance + Asynchronously create the SafelistInstance and return response metadata - :param phone_number: The phone number to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :returns: True if delete succeeds, False otherwise + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self, phone_number: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -121,19 +164,41 @@ def delete(self, phone_number: Union[str, object] = values.unset) -> bool: "PhoneNumber": phone_number, } ) - return self._version.delete( + return self._version.delete_with_response_info( method="DELETE", uri=self._uri, headers=headers, params=params ) - async def delete_async( - self, phone_number: Union[str, object] = values.unset - ) -> bool: + def delete(self, phone_number: Union[str, object] = values.unset) -> bool: """ - Asynchronously delete the SafelistInstance + Delete the SafelistInstance - :param phone_number: The phone number to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(phone_number=phone_number) + return success + + def delete_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Delete the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(phone_number=phone_number) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) params = values.of( @@ -141,18 +206,42 @@ async def delete_async( "PhoneNumber": phone_number, } ) - return await self._version.delete_async( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers, params=params ) - def fetch( + async def delete_async( self, phone_number: Union[str, object] = values.unset - ) -> SafelistInstance: + ) -> bool: """ - Asynchronously fetch the SafelistInstance + Asynchronously delete the SafelistInstance - :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :returns: The fetched SafelistInstance + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(phone_number=phone_number) + return success + + async def delete_with_http_info_async( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously delete the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + phone_number=phone_number + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, phone_number: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -164,21 +253,44 @@ def fetch( } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) - return SafelistInstance(self._version, payload) - - async def fetch_async( + def fetch( self, phone_number: Union[str, object] = values.unset ) -> SafelistInstance: """ - Asynchronously fetch the SafelistInstance + Fetch the SafelistInstance - :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: The fetched SafelistInstance """ + payload, _, _ = self._fetch(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + def fetch_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" @@ -189,12 +301,37 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + Asynchronously fetch the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: The fetched SafelistInstance + """ + payload, _, _ = await self._fetch_async(phone_number=phone_number) return SafelistInstance(self._version, payload) + async def fetch_with_http_info_async( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/accounts/v1/secondary_auth_token.py b/twilio/rest/accounts/v1/secondary_auth_token.py index f5e2b5c1a3..c50297211d 100644 --- a/twilio/rest/accounts/v1/secondary_auth_token.py +++ b/twilio/rest/accounts/v1/secondary_auth_token.py @@ -13,8 +13,9 @@ """ from datetime import datetime -from typing import Any, Dict, Optional -from twilio.base import deserialize, values +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -59,41 +60,117 @@ def _proxy(self) -> "SecondaryAuthTokenContext": ) return self._context - def create(self) -> "SecondaryAuthTokenInstance": + def create( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> "SecondaryAuthTokenInstance": """ Create the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The created SecondaryAuthTokenInstance """ - return self._proxy.create() + return self._proxy.create( + suppress_email_notification=suppress_email_notification, + ) - async def create_async(self) -> "SecondaryAuthTokenInstance": + async def create_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> "SecondaryAuthTokenInstance": """ Asynchronous coroutine to create the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The created SecondaryAuthTokenInstance """ - return await self._proxy.create_async() + return await self._proxy.create_async( + suppress_email_notification=suppress_email_notification, + ) + + def create_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + suppress_email_notification=suppress_email_notification, + ) + + async def create_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. - def delete(self) -> bool: + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + suppress_email_notification=suppress_email_notification, + ) + + def delete( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> bool: """ Deletes the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: True if delete succeeds, False otherwise """ - return self._proxy.delete() + return self._proxy.delete( + suppress_email_notification=suppress_email_notification, + ) - async def delete_async(self) -> bool: + async def delete_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: True if delete succeeds, False otherwise """ - return await self._proxy.delete_async() + return await self._proxy.delete_async( + suppress_email_notification=suppress_email_notification, + ) + + def delete_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + suppress_email_notification=suppress_email_notification, + ) + + async def delete_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance with HTTP info + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + suppress_email_notification=suppress_email_notification, + ) def __repr__(self) -> str: """ @@ -117,59 +194,229 @@ def __init__(self, version: Version): self._uri = "/AuthTokens/Secondary" - def create(self) -> SecondaryAuthTokenInstance: + def _create( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> SecondaryAuthTokenInstance: """ Create the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The created SecondaryAuthTokenInstance """ - data = values.of({}) + payload, _, _ = self._create( + suppress_email_notification=suppress_email_notification + ) + return SecondaryAuthTokenInstance(self._version, payload) - payload = self._version.create(method="POST", uri=self._uri, data=data) + def create_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance and return response metadata - return SecondaryAuthTokenInstance(self._version, payload) + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + suppress_email_notification=suppress_email_notification + ) + instance = SecondaryAuthTokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - async def create_async(self) -> SecondaryAuthTokenInstance: + async def _create_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> SecondaryAuthTokenInstance: """ Asynchronous coroutine to create the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: The created SecondaryAuthTokenInstance """ - data = values.of({}) + payload, _, _ = await self._create_async( + suppress_email_notification=suppress_email_notification + ) + return SecondaryAuthTokenInstance(self._version, payload) + + async def create_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + suppress_email_notification=suppress_email_notification ) + instance = SecondaryAuthTokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - return SecondaryAuthTokenInstance(self._version, payload) + def _delete( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) - def delete(self) -> bool: + params = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def delete( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> bool: """ Deletes the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete( + suppress_email_notification=suppress_email_notification + ) + return success + + def delete_with_http_info( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance and return response metadata + + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + suppress_email_notification=suppress_email_notification + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + params = values.of( + { + "SuppressEmailNotification": serialize.boolean_to_string( + suppress_email_notification + ), + } + ) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) - async def delete_async(self) -> bool: + async def delete_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async( + suppress_email_notification=suppress_email_notification + ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, suppress_email_notification: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + :param suppress_email_notification: Whether to suppress the email notification that Twilio sends to the owners and administrators of the account about this Auth Token change. Defaults to `false`, so Twilio sends the email. Set to `true` when rotating Auth Tokens across many subaccounts. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + suppress_email_notification=suppress_email_notification ) + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/__init__.py b/twilio/rest/api/v2010/account/__init__.py index 7c7e2c1069..0aa9ecd0b0 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -99,6 +100,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AccountContext] = None @property @@ -134,6 +136,24 @@ async def fetch_async(self) -> "AccountInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -170,6 +190,42 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the AccountInstance with HTTP info + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + status=status, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountInstance with HTTP info + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + status=status, + ) + @property def addresses(self) -> AddressList: """ @@ -390,60 +446,106 @@ def __init__(self, version: Version, sid: str): self._usage: Optional[UsageList] = None self._validation_requests: Optional[ValidationRequestList] = None - def fetch(self) -> AccountInstance: + def _fetch(self) -> tuple: """ - Fetch the AccountInstance - + Internal helper for fetch operation - :returns: The fetched AccountInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = self._fetch() return AccountInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AccountInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AccountInstance + Fetch the AccountInstance and return response metadata - :returns: The fetched AccountInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = await self._fetch_async() return AccountInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, status: Union["AccountInstance.Status", object] = values.unset, - ) -> AccountInstance: + ) -> tuple: """ - Update the AccountInstance + Internal helper for update operation - :param friendly_name: Update the human-readable description of this Account - :param status: - - :returns: The updated AccountInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -458,25 +560,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AccountInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, status: Union["AccountInstance.Status", object] = values.unset, ) -> AccountInstance: """ - Asynchronous coroutine to update the AccountInstance + Update the AccountInstance :param friendly_name: Update the human-readable description of this Account :param status: :returns: The updated AccountInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, status=status) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the AccountInstance and return response metadata + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, status=status + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -490,12 +623,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, status=status + ) return AccountInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountInstance and return response metadata + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, status=status + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def addresses(self) -> AddressList: """ @@ -802,6 +970,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: :param payload: Payload response from the API """ + return AccountInstance(self._version, payload) def __repr__(self) -> str: @@ -826,15 +995,12 @@ def __init__(self, version: Version): self._uri = "/Accounts.json" - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> AccountInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the AccountInstance - - :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + Internal helper for create operation - :returns: The created AccountInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -848,22 +1014,46 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AccountInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset ) -> AccountInstance: """ - Asynchronously create the AccountInstance + Create the AccountInstance :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` :returns: The created AccountInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return AccountInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -876,12 +1066,39 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return AccountInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -944,6 +1161,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AccountInstance and returns headers from first page + + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AccountInstance and returns headers from first page + + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -967,6 +1244,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -999,6 +1277,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1009,6 +1288,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AccountInstance and returns headers from first page + + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AccountInstance and returns headers from first page + + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -1087,6 +1428,88 @@ async def page_async( ) return AccountPage(self._version, response) + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AccountPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AccountPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AccountPage: """ Retrieve a specific page of AccountInstance records from the API. diff --git a/twilio/rest/api/v2010/account/address/__init__.py b/twilio/rest/api/v2010/account/address/__init__.py index b97628fe87..c309d54844 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[AddressContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AddressInstance": """ Fetch the AddressInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "AddressInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -148,7 +186,7 @@ def update( """ Update the AddressInstance - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param customer_name: The name to associate with the address. :param street: The number and street address of the address. :param city: The city of the address. @@ -187,7 +225,7 @@ async def update_async( """ Asynchronous coroutine to update the AddressInstance - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param customer_name: The name to associate with the address. :param street: The number and street address of the address. :param city: The city of the address. @@ -211,6 +249,84 @@ async def update_async( street_secondary=street_secondary, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AddressInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + @property def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ @@ -251,6 +367,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AddressInstance @@ -258,10 +388,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -270,27 +422,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AddressInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AddressInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AddressInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressInstance: + """ + Fetch the AddressInstance + + :returns: The fetched AddressInstance + """ + payload, _, _ = self._fetch() return AddressInstance( self._version, payload, @@ -298,22 +466,46 @@ def fetch(self) -> AddressInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AddressInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AddressInstance + Fetch the AddressInstance and return response metadata - :returns: The fetched AddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AddressInstance: + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + payload, _, _ = await self._fetch_async() return AddressInstance( self._version, payload, @@ -321,7 +513,23 @@ async def fetch_async(self) -> AddressInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, customer_name: Union[str, object] = values.unset, @@ -332,21 +540,12 @@ def update( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> tuple: """ - Update the AddressInstance - - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. - :param customer_name: The name to associate with the address. - :param street: The number and street address of the address. - :param city: The city of the address. - :param region: The state or region of the address. - :param postal_code: The postal code of the address. - :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. - :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. - :param street_secondary: The additional number and street address of the address. + Internal helper for update operation - :returns: The updated AddressInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,10 +567,48 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) return AddressInstance( self._version, payload, @@ -379,7 +616,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, customer_name: Union[str, object] = values.unset, @@ -390,11 +627,11 @@ async def update_async( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AddressInstance + Update the AddressInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param customer_name: The name to associate with the address. :param street: The number and street address of the address. :param city: The city of the address. @@ -404,7 +641,44 @@ async def update_async( :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. :param street_secondary: The additional number and street address of the address. - :returns: The updated AddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -426,19 +700,103 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return AddressInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - @property - def dependent_phone_numbers(self) -> DependentPhoneNumberList: + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ Access the dependent_phone_numbers """ @@ -468,6 +826,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: :param payload: Payload response from the API """ + return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -499,7 +858,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Addresses.json".format(**self._solution) - def create( + def _create( self, customer_name: str, street: str, @@ -511,22 +870,12 @@ def create( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> tuple: """ - Create the AddressInstance - - :param customer_name: The name to associate with the new address. - :param street: The number and street address of the new address. - :param city: The city of the new address. - :param region: The state or region of the new address. - :param postal_code: The postal code of the new address. - :param iso_country: The ISO country code of the new address. - :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. - :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. - :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. - :param street_secondary: The additional number and street address of the address. + Internal helper for create operation - :returns: The created AddressInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -549,15 +898,56 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + payload, _, _ = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, customer_name: str, street: str, @@ -569,9 +959,9 @@ async def create_async( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> ApiResponse: """ - Asynchronously create the AddressInstance + Create the AddressInstance and return response metadata :param customer_name: The name to associate with the new address. :param street: The number and street address of the new address. @@ -579,12 +969,48 @@ async def create_async( :param region: The state or region of the new address. :param postal_code: The postal code of the new address. :param iso_country: The ISO country code of the new address. - :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. :param street_secondary: The additional number and street address of the address. - :returns: The created AddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -607,18 +1033,106 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronously create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + payload, _, _ = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AddressInstance and return response metadata + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -631,6 +1145,7 @@ def stream( :param str customer_name: The `customer_name` of the Address resources to read. :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. :param str iso_country: The ISO country code of the Address resources to read. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit @@ -645,6 +1160,7 @@ def stream( page = self.page( customer_name=customer_name, friendly_name=friendly_name, + emergency_enabled=emergency_enabled, iso_country=iso_country, page_size=limits["page_size"], ) @@ -655,6 +1171,7 @@ async def stream_async( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -667,6 +1184,7 @@ async def stream_async( :param str customer_name: The `customer_name` of the Address resources to read. :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. :param str iso_country: The ISO country code of the Address resources to read. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit @@ -681,16 +1199,94 @@ async def stream_async( page = await self.page_async( customer_name=customer_name, friendly_name=friendly_name, + emergency_enabled=emergency_enabled, iso_country=iso_country, page_size=limits["page_size"], ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AddressInstance and returns headers from first page + + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AddressInstance and returns headers from first page + + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -702,6 +1298,7 @@ def list( :param str customer_name: The `customer_name` of the Address resources to read. :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. :param str iso_country: The ISO country code of the Address resources to read. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit @@ -712,10 +1309,12 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( customer_name=customer_name, friendly_name=friendly_name, + emergency_enabled=emergency_enabled, iso_country=iso_country, limit=limit, page_size=page_size, @@ -726,6 +1325,7 @@ async def list_async( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -737,6 +1337,7 @@ async def list_async( :param str customer_name: The `customer_name` of the Address resources to read. :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. :param str iso_country: The ISO country code of the Address resources to read. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit @@ -747,21 +1348,98 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( customer_name=customer_name, friendly_name=friendly_name, + emergency_enabled=emergency_enabled, iso_country=iso_country, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AddressInstance and returns headers from first page + + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AddressInstance and returns headers from first page + + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, @@ -773,6 +1451,7 @@ def page( :param customer_name: The `customer_name` of the Address resources to read. :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. :param iso_country: The ISO country code of the Address resources to read. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state @@ -784,6 +1463,7 @@ def page( { "CustomerName": customer_name, "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), "IsoCountry": iso_country, "PageToken": page_token, "Page": page_number, @@ -798,12 +1478,13 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AddressPage(self._version, response, self._solution) + return AddressPage(self._version, response, solution=self._solution) async def page_async( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, @@ -815,6 +1496,7 @@ async def page_async( :param customer_name: The `customer_name` of the Address resources to read. :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. :param iso_country: The ISO country code of the Address resources to read. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state @@ -826,6 +1508,7 @@ async def page_async( { "CustomerName": customer_name, "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), "IsoCountry": iso_country, "PageToken": page_token, "Page": page_number, @@ -840,7 +1523,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AddressPage(self._version, response, self._solution) + return AddressPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddressPage, status code, and headers + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddressPage, status code, and headers + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AddressPage: """ @@ -852,7 +1629,7 @@ def get_page(self, target_url: str) -> AddressPage: :returns: Page of AddressInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AddressPage(self._version, response, self._solution) + return AddressPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AddressPage: """ @@ -864,7 +1641,7 @@ async def get_page_async(self, target_url: str) -> AddressPage: :returns: Page of AddressInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AddressPage(self._version, response, self._solution) + return AddressPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AddressContext: """ diff --git a/twilio/rest/api/v2010/account/address/dependent_phone_number.py b/twilio/rest/api/v2010/account/address/dependent_phone_number.py index 504e69bc92..9a21e34d7c 100644 --- a/twilio/rest/api/v2010/account/address/dependent_phone_number.py +++ b/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -134,6 +135,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: :param payload: Payload response from the API """ + return DependentPhoneNumberInstance( self._version, payload, @@ -222,6 +224,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -241,6 +293,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -267,6 +320,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -275,6 +329,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -306,7 +410,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentPhoneNumberPage(self._version, response, self._solution) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -339,7 +445,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentPhoneNumberPage(self._version, response, self._solution) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DependentPhoneNumberPage: """ @@ -351,7 +533,9 @@ def get_page(self, target_url: str) -> DependentPhoneNumberPage: :returns: Page of DependentPhoneNumberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DependentPhoneNumberPage(self._version, response, self._solution) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: """ @@ -363,7 +547,9 @@ async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: :returns: Page of DependentPhoneNumberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DependentPhoneNumberPage(self._version, response, self._solution) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/application.py b/twilio/rest/api/v2010/account/application.py index 555ab72b4a..ba5a7926de 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ApplicationContext] = None @property @@ -130,6 +132,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApplicationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApplicationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ApplicationInstance": """ Fetch the ApplicationInstance @@ -148,6 +168,24 @@ async def fetch_async(self) -> "ApplicationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -268,6 +306,126 @@ async def update_async( public_application_connect_enabled=public_application_connect_enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApplicationInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApplicationInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -299,6 +457,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ApplicationInstance @@ -306,10 +478,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApplicationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -318,27 +512,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApplicationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ApplicationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ApplicationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ApplicationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApplicationInstance: + """ + Fetch the ApplicationInstance + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = self._fetch() return ApplicationInstance( self._version, payload, @@ -346,22 +556,46 @@ def fetch(self) -> ApplicationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ApplicationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ApplicationInstance + Fetch the ApplicationInstance and return response metadata - :returns: The fetched ApplicationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ApplicationInstance: + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = await self._fetch_async() return ApplicationInstance( self._version, payload, @@ -369,7 +603,23 @@ async def fetch_async(self) -> ApplicationInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -387,28 +637,12 @@ def update( sms_status_callback: Union[str, object] = values.unset, message_status_callback: Union[str, object] = values.unset, public_application_connect_enabled: Union[bool, object] = values.unset, - ) -> ApplicationInstance: + ) -> tuple: """ - Update the ApplicationInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. - :param voice_url: The URL we should call when the phone number assigned to this application receives a call. - :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. - :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. - :param sms_url: The URL we should call when the phone number receives an incoming SMS message. - :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. - :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. - :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. - :param message_status_callback: The URL we should call using a POST method to send message status information to your application. - :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + Internal helper for update operation - :returns: The updated ApplicationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -441,18 +675,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -472,7 +699,7 @@ async def update_async( public_application_connect_enabled: Union[bool, object] = values.unset, ) -> ApplicationInstance: """ - Asynchronous coroutine to update the ApplicationInstance + Update the ApplicationInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. @@ -493,11 +720,128 @@ async def update_async( :returns: The updated ApplicationInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) - data = values.of( - { - "FriendlyName": friendly_name, - "ApiVersion": api_version, + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApplicationInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, "VoiceUrl": voice_url, "VoiceMethod": voice_method, "VoiceFallbackUrl": voice_fallback_url, @@ -524,10 +868,69 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronous coroutine to update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) return ApplicationInstance( self._version, payload, @@ -535,6 +938,73 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApplicationInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + instance = ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -553,6 +1023,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: :param payload: Payload response from the API """ + return ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -578,13 +1049,260 @@ def __init__(self, version: Version, account_sid: str): """ super().__init__(version) - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + + def _create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + payload, _, _ = self._create( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ApplicationInstance and return response metadata + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, + ) + instance = ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def create( + async def create_async( self, api_version: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -604,7 +1322,7 @@ def create( public_application_connect_enabled: Union[bool, object] = values.unset, ) -> ApplicationInstance: """ - Create the ApplicationInstance + Asynchronously create the ApplicationInstance :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. :param voice_url: The URL we should call when the phone number assigned to this application receives a call. @@ -625,46 +1343,29 @@ def create( :returns: The created ApplicationInstance """ - - data = values.of( - { - "ApiVersion": api_version, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "VoiceCallerIdLookup": serialize.boolean_to_string( - voice_caller_id_lookup - ), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsStatusCallback": sms_status_callback, - "MessageStatusCallback": message_status_callback, - "FriendlyName": friendly_name, - "PublicApplicationConnectEnabled": serialize.boolean_to_string( - public_application_connect_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, ) - return ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + async def create_with_http_info_async( self, api_version: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -682,9 +1383,9 @@ async def create_async( message_status_callback: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, public_application_connect_enabled: Union[bool, object] = values.unset, - ) -> ApplicationInstance: + ) -> ApiResponse: """ - Asynchronously create the ApplicationInstance + Asynchronously create the ApplicationInstance and return response metadata :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. :param voice_url: The URL we should call when the phone number assigned to this application receives a call. @@ -703,46 +1404,30 @@ async def create_async( :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. - :returns: The created ApplicationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ApiVersion": api_version, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "VoiceCallerIdLookup": serialize.boolean_to_string( - voice_caller_id_lookup - ), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsStatusCallback": sms_status_callback, - "MessageStatusCallback": message_status_callback, - "FriendlyName": friendly_name, - "PublicApplicationConnectEnabled": serialize.boolean_to_string( - public_application_connect_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, ) - - return ApplicationInstance( + instance = ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -800,6 +1485,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ApplicationInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ApplicationInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -821,6 +1562,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -850,6 +1592,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -859,6 +1602,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ApplicationInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ApplicationInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -893,7 +1692,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ApplicationPage(self._version, response, self._solution) + return ApplicationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -929,7 +1728,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ApplicationPage(self._version, response, self._solution) + return ApplicationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ApplicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ApplicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ApplicationPage: """ @@ -941,7 +1816,7 @@ def get_page(self, target_url: str) -> ApplicationPage: :returns: Page of ApplicationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ApplicationPage(self._version, response, self._solution) + return ApplicationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ApplicationPage: """ @@ -953,7 +1828,7 @@ async def get_page_async(self, target_url: str) -> ApplicationPage: :returns: Page of ApplicationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ApplicationPage(self._version, response, self._solution) + return ApplicationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ApplicationContext: """ diff --git a/twilio/rest/api/v2010/account/authorized_connect_app.py b/twilio/rest/api/v2010/account/authorized_connect_app.py index cceb694c10..b608e9f141 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "account_sid": account_sid, "connect_app_sid": connect_app_sid or self.connect_app_sid, } + self._context: Optional[AuthorizedConnectAppContext] = None @property @@ -106,6 +108,24 @@ async def fetch_async(self) -> "AuthorizedConnectAppInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizedConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -137,20 +157,30 @@ def __init__(self, version: Version, account_sid: str, connect_app_sid: str): **self._solution ) - def fetch(self) -> AuthorizedConnectAppInstance: + def _fetch(self) -> tuple: """ - Fetch the AuthorizedConnectAppInstance - + Internal helper for fetch operation - :returns: The fetched AuthorizedConnectAppInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AuthorizedConnectAppInstance: + """ + Fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + payload, _, _ = self._fetch() return AuthorizedConnectAppInstance( self._version, payload, @@ -158,22 +188,46 @@ def fetch(self) -> AuthorizedConnectAppInstance: connect_app_sid=self._solution["connect_app_sid"], ) - async def fetch_async(self) -> AuthorizedConnectAppInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + Fetch the AuthorizedConnectAppInstance and return response metadata - :returns: The fetched AuthorizedConnectAppInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthorizedConnectAppInstance: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + payload, _, _ = await self._fetch_async() return AuthorizedConnectAppInstance( self._version, payload, @@ -181,6 +235,22 @@ async def fetch_async(self) -> AuthorizedConnectAppInstance: connect_app_sid=self._solution["connect_app_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -199,6 +269,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: :param payload: Payload response from the API """ + return AuthorizedConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -282,6 +353,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -301,6 +422,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -327,6 +449,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -335,6 +458,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthorizedConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -366,7 +539,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AuthorizedConnectAppPage(self._version, response, self._solution) + return AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -399,7 +574,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AuthorizedConnectAppPage(self._version, response, self._solution) + return AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizedConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizedConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AuthorizedConnectAppPage: """ @@ -411,7 +662,9 @@ def get_page(self, target_url: str) -> AuthorizedConnectAppPage: :returns: Page of AuthorizedConnectAppInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AuthorizedConnectAppPage(self._version, response, self._solution) + return AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> AuthorizedConnectAppPage: """ @@ -423,7 +676,9 @@ async def get_page_async(self, target_url: str) -> AuthorizedConnectAppPage: :returns: Page of AuthorizedConnectAppInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AuthorizedConnectAppPage(self._version, response, self._solution) + return AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) def get(self, connect_app_sid: str) -> AuthorizedConnectAppContext: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py index fc2a6f0600..4b8207514d 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "account_sid": account_sid, "country_code": country_code or self.country_code, } + self._context: Optional[AvailablePhoneNumberCountryContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "AvailablePhoneNumberCountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def local(self) -> LocalList: """ @@ -196,20 +216,30 @@ def __init__(self, version: Version, account_sid: str, country_code: str): self._toll_free: Optional[TollFreeList] = None self._voip: Optional[VoipList] = None - def fetch(self) -> AvailablePhoneNumberCountryInstance: + def _fetch(self) -> tuple: """ - Fetch the AvailablePhoneNumberCountryInstance - + Internal helper for fetch operation - :returns: The fetched AvailablePhoneNumberCountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AvailablePhoneNumberCountryInstance: + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + payload, _, _ = self._fetch() return AvailablePhoneNumberCountryInstance( self._version, payload, @@ -217,22 +247,46 @@ def fetch(self) -> AvailablePhoneNumberCountryInstance: country_code=self._solution["country_code"], ) - async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + Fetch the AvailablePhoneNumberCountryInstance and return response metadata - :returns: The fetched AvailablePhoneNumberCountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + payload, _, _ = await self._fetch_async() return AvailablePhoneNumberCountryInstance( self._version, payload, @@ -240,6 +294,22 @@ async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: country_code=self._solution["country_code"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def local(self) -> LocalList: """ @@ -353,6 +423,7 @@ def get_instance( :param payload: Payload response from the API """ + return AvailablePhoneNumberCountryInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -436,6 +507,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -455,6 +576,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -481,6 +603,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -489,6 +612,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailablePhoneNumberCountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -520,7 +693,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + return AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -553,7 +728,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + return AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AvailablePhoneNumberCountryPage: """ @@ -565,7 +816,9 @@ def get_page(self, target_url: str) -> AvailablePhoneNumberCountryPage: :returns: Page of AvailablePhoneNumberCountryInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + return AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> AvailablePhoneNumberCountryPage: """ @@ -577,7 +830,9 @@ async def get_page_async(self, target_url: str) -> AvailablePhoneNumberCountryPa :returns: Page of AvailablePhoneNumberCountryInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + return AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) def get(self, country_code: str) -> AvailablePhoneNumberCountryContext: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/local.py b/twilio/rest/api/v2010/account/available_phone_number_country/local.py index 4f0b2e7991..dd014b8221 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/local.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/local.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> LocalPage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> LocalPage: :returns: Page of LocalInstance """ response = self._version.domain.twilio.request("GET", target_url) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> LocalPage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> LocalPage: :returns: Page of LocalInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py index 5695c917c3..8413389849 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MachineToMachineInstance: :param payload: Payload response from the API """ + return MachineToMachineInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MachineToMachinePage(self._version, response, self._solution) + return MachineToMachinePage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MachineToMachinePage(self._version, response, self._solution) + return MachineToMachinePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MachineToMachinePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MachineToMachinePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MachineToMachinePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MachineToMachinePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MachineToMachinePage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> MachineToMachinePage: :returns: Page of MachineToMachineInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MachineToMachinePage(self._version, response, self._solution) + return MachineToMachinePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MachineToMachinePage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> MachineToMachinePage: :returns: Page of MachineToMachineInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MachineToMachinePage(self._version, response, self._solution) + return MachineToMachinePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py index 2382155ee5..393c3433a5 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MobilePage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> MobilePage: :returns: Page of MobileInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MobilePage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> MobilePage: :returns: Page of MobileInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/national.py b/twilio/rest/api/v2010/account/available_phone_number_country/national.py index a5e926425a..1f1bf33a76 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/national.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/national.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NationalInstance: :param payload: Payload response from the API """ + return NationalInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return NationalPage(self._version, response, self._solution) + return NationalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return NationalPage(self._version, response, self._solution) + return NationalPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NationalPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NationalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NationalPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NationalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> NationalPage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> NationalPage: :returns: Page of NationalInstance """ response = self._version.domain.twilio.request("GET", target_url) - return NationalPage(self._version, response, self._solution) + return NationalPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> NationalPage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> NationalPage: :returns: Page of NationalInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return NationalPage(self._version, response, self._solution) + return NationalPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py index 3a9c02bab4..fa9e3332c8 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SharedCostInstance: :param payload: Payload response from the API """ + return SharedCostInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SharedCostPage(self._version, response, self._solution) + return SharedCostPage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SharedCostPage(self._version, response, self._solution) + return SharedCostPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SharedCostPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SharedCostPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SharedCostPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SharedCostPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SharedCostPage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> SharedCostPage: :returns: Page of SharedCostInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SharedCostPage(self._version, response, self._solution) + return SharedCostPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SharedCostPage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> SharedCostPage: :returns: Page of SharedCostInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SharedCostPage(self._version, response, self._solution) + return SharedCostPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py index de4a2d9885..de41071b08 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TollFreePage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> TollFreePage: :returns: Page of TollFreeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TollFreePage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> TollFreePage: :returns: Page of TollFreeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/voip.py b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py index 9ebfae5396..0c319a53df 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/voip.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VoipInstance: :param payload: Payload response from the API """ + return VoipInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -536,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return VoipPage(self._version, response, self._solution) + return VoipPage(self._version, response, solution=self._solution) async def page_async( self, @@ -567,7 +889,7 @@ async def page_async( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -629,7 +951,197 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return VoipPage(self._version, response, self._solution) + return VoipPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VoipPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VoipPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VoipPage, status code, and headers + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VoipPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> VoipPage: """ @@ -641,7 +1153,7 @@ def get_page(self, target_url: str) -> VoipPage: :returns: Page of VoipInstance """ response = self._version.domain.twilio.request("GET", target_url) - return VoipPage(self._version, response, self._solution) + return VoipPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> VoipPage: """ @@ -653,7 +1165,7 @@ async def get_page_async(self, target_url: str) -> VoipPage: :returns: Page of VoipInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return VoipPage(self._version, response, self._solution) + return VoipPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/balance.py b/twilio/rest/api/v2010/account/balance.py index 66bb91e9f9..106e76e33d 100644 --- a/twilio/rest/api/v2010/account/balance.py +++ b/twilio/rest/api/v2010/account/balance.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,42 +67,86 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Balance.json".format(**self._solution) - def fetch(self) -> BalanceInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the BalanceInstance - + Internal helper for fetch operation - :returns: The fetched BalanceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BalanceInstance: + """ + Fetch the BalanceInstance + + :returns: The fetched BalanceInstance + """ + payload, _, _ = self._fetch() return BalanceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def fetch_async(self) -> BalanceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the BalanceInstance + Fetch the BalanceInstance and return response metadata - :returns: The fetched BalanceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BalanceInstance: + """ + Asynchronously fetch the BalanceInstance + + + :returns: The fetched BalanceInstance + """ + payload, _, _ = await self._fetch_async() return BalanceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the BalanceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/call/__init__.py b/twilio/rest/api/v2010/account/call/__init__.py index b09550c326..6cba76bf52 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -130,6 +131,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -166,6 +168,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CallInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CallInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CallInstance": """ Fetch the CallInstance @@ -184,6 +204,24 @@ async def fetch_async(self) -> "CallInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, url: Union[str, object] = values.unset, @@ -262,6 +300,84 @@ async def update_async( time_limit=time_limit, ) + def update_with_http_info( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the CallInstance with HTTP info + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + async def update_with_http_info_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance with HTTP info + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + @property def events(self) -> EventList: """ @@ -366,6 +482,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): UserDefinedMessageSubscriptionList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CallInstance @@ -373,10 +503,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CallInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -385,27 +537,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CallInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CallInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CallInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CallInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + :returns: The fetched CallInstance + """ + payload, _, _ = self._fetch() return CallInstance( self._version, payload, @@ -413,22 +581,46 @@ def fetch(self) -> CallInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CallInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CallInstance + Fetch the CallInstance and return response metadata - :returns: The fetched CallInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + payload, _, _ = await self._fetch_async() return CallInstance( self._version, payload, @@ -436,7 +628,23 @@ async def fetch_async(self) -> CallInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, url: Union[str, object] = values.unset, method: Union[str, object] = values.unset, @@ -447,21 +655,12 @@ def update( status_callback_method: Union[str, object] = values.unset, twiml: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, - ) -> CallInstance: + ) -> tuple: """ - Update the CallInstance - - :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). - :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param status: - :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. - :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). - :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive - :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + Internal helper for update operation - :returns: The updated CallInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -483,10 +682,48 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + payload, _, _ = self._update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) return CallInstance( self._version, payload, @@ -494,7 +731,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, url: Union[str, object] = values.unset, method: Union[str, object] = values.unset, @@ -505,9 +742,9 @@ async def update_async( status_callback_method: Union[str, object] = values.unset, twiml: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, - ) -> CallInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the CallInstance + Update the CallInstance and return response metadata :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. @@ -519,7 +756,44 @@ async def update_async( :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. - :returns: The updated CallInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -541,27 +815,111 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return CallInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - @property - def events(self) -> EventList: - """ - Access the events - """ - if self._events is None: - self._events = EventList( - self._version, - self._solution["account_sid"], - self._solution["sid"], + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + payload, _, _ = await self._update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance and return response metadata + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["account_sid"], + self._solution["sid"], ) return self._events @@ -689,6 +1047,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CallInstance: :param payload: Payload response from the API """ + return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -720,7 +1079,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Calls.json".format(**self._solution) - def create( + def _create( self, to: str, from_: str, @@ -736,6 +1095,7 @@ def create( recording_channels: Union[str, object] = values.unset, recording_status_callback: Union[str, object] = values.unset, recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, sip_auth_username: Union[str, object] = values.unset, sip_auth_password: Union[str, object] = values.unset, machine_detection: Union[str, object] = values.unset, @@ -749,55 +1109,22 @@ def create( async_amd: Union[str, object] = values.unset, async_amd_status_callback: Union[str, object] = values.unset, async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, byoc: Union[str, object] = values.unset, call_reason: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, url: Union[str, object] = values.unset, twiml: Union[str, object] = values.unset, application_sid: Union[str, object] = values.unset, - ) -> CallInstance: + ) -> tuple: """ - Create the CallInstance - - :param to: The phone number, SIP address, or client identifier to call. - :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. - :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. - :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). - :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. - :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param send_digits: A string of keys to dial after connecting to the number, maximum of 32 digits. Valid digits in the string include: any digit (`0`-`9`), '`#`', '`*`' and '`w`', to insert a half second pause. For example, if you connected to a company phone number and wanted to pause for one second, and then dial extension 1234 followed by the pound key, the value of this parameter would be `ww1234#`. Remember to URL-encode this string, since the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. - :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. - :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. - :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. - :param recording_status_callback: The URL that we call when the recording is available to be accessed. - :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. - :param sip_auth_username: The username used to authenticate the caller making a SIP call. - :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. - :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). - :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. - :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. - :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. - :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. - :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. - :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. - :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. - :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. - :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. - :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. - :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) - :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) - :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. - :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. - :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. - :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). - :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. - :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + Internal helper for create operation - :returns: The created CallInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -818,6 +1145,7 @@ def create( "RecordingChannels": recording_channels, "RecordingStatusCallback": recording_status_callback, "RecordingStatusCallbackMethod": recording_status_callback_method, + "RecordingConfigurationId": recording_configuration_id, "SipAuthUsername": sip_auth_username, "SipAuthPassword": sip_auth_password, "MachineDetection": machine_detection, @@ -833,11 +1161,13 @@ def create( "AsyncAmd": async_amd, "AsyncAmdStatusCallback": async_amd_status_callback, "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Passports": passports, "Byoc": byoc, "CallReason": call_reason, "CallToken": call_token, "RecordingTrack": recording_track, "TimeLimit": time_limit, + "ClientNotificationUrl": client_notification_url, "Url": url, "Twiml": twiml, "ApplicationSid": application_sid, @@ -849,15 +1179,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CallInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - - async def create_async( + def create( self, to: str, from_: str, @@ -873,6 +1199,7 @@ async def create_async( recording_channels: Union[str, object] = values.unset, recording_status_callback: Union[str, object] = values.unset, recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, sip_auth_username: Union[str, object] = values.unset, sip_auth_password: Union[str, object] = values.unset, machine_detection: Union[str, object] = values.unset, @@ -886,17 +1213,19 @@ async def create_async( async_amd: Union[str, object] = values.unset, async_amd_status_callback: Union[str, object] = values.unset, async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, byoc: Union[str, object] = values.unset, call_reason: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, url: Union[str, object] = values.unset, twiml: Union[str, object] = values.unset, application_sid: Union[str, object] = values.unset, ) -> CallInstance: """ - Asynchronously create the CallInstance + Create the CallInstance :param to: The phone number, SIP address, or client identifier to call. :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. @@ -906,12 +1235,13 @@ async def create_async( :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. - :param send_digits: A string of keys to dial after connecting to the number, maximum of 32 digits. Valid digits in the string include: any digit (`0`-`9`), '`#`', '`*`' and '`w`', to insert a half second pause. For example, if you connected to a company phone number and wanted to pause for one second, and then dial extension 1234 followed by the pound key, the value of this parameter would be `ww1234#`. Remember to URL-encode this string, since the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. :param recording_status_callback: The URL that we call when the recording is available to be accessed. :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording :param sip_auth_username: The username used to authenticate the caller making a SIP call. :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). @@ -925,106 +1255,644 @@ async def create_async( :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param client_notification_url: The URL that we should use to deliver `push call notification`. :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. :returns: The created CallInstance """ - - data = values.of( - { - "To": to, - "From": from_, - "Method": method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "StatusCallbackMethod": status_callback_method, - "SendDigits": send_digits, - "Timeout": timeout, - "Record": serialize.boolean_to_string(record), - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "MachineDetection": machine_detection, - "MachineDetectionTimeout": machine_detection_timeout, - "RecordingStatusCallbackEvent": serialize.map( - recording_status_callback_event, lambda e: e - ), - "Trim": trim, - "CallerId": caller_id, - "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, - "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, - "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, - "AsyncAmd": async_amd, - "AsyncAmdStatusCallback": async_amd_status_callback, - "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, - "Byoc": byoc, - "CallReason": call_reason, - "CallToken": call_token, - "RecordingTrack": recording_track, - "TimeLimit": time_limit, - "Url": url, - "Twiml": twiml, - "ApplicationSid": application_sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._create( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + passports=passports, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, ) - return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - def stream( + def create_with_http_info( self, - to: Union[str, object] = values.unset, - from_: Union[str, object] = values.unset, - parent_call_sid: Union[str, object] = values.unset, - status: Union["CallInstance.Status", object] = values.unset, - start_time: Union[datetime, object] = values.unset, - start_time_before: Union[datetime, object] = values.unset, - start_time_after: Union[datetime, object] = values.unset, - end_time: Union[datetime, object] = values.unset, - end_time_before: Union[datetime, object] = values.unset, - end_time_after: Union[datetime, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[CallInstance]: + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Streams CallInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Create the CallInstance and return response metadata + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + passports=passports, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + instance = CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "From": from_, + "Method": method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "StatusCallbackMethod": status_callback_method, + "SendDigits": send_digits, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "RecordingConfigurationId": recording_configuration_id, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "Trim": trim, + "CallerId": caller_id, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AsyncAmd": async_amd, + "AsyncAmdStatusCallback": async_amd_status_callback, + "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Passports": passports, + "Byoc": byoc, + "CallReason": call_reason, + "CallToken": call_token, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "ClientNotificationUrl": client_notification_url, + "Url": url, + "Twiml": twiml, + "ApplicationSid": application_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: + """ + Asynchronously create the CallInstance + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: The created CallInstance + """ + payload, _, _ = await self._create_async( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + passports=passports, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CallInstance and return response metadata + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + passports=passports, + byoc=byoc, + call_reason=call_reason, + call_token=call_token, + recording_track=recording_track, + time_limit=time_limit, + client_notification_url=client_notification_url, + url=url, + twiml=twiml, + application_sid=application_sid, + ) + instance = CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CallInstance]: + """ + Streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallInstance]: + """ + Asynchronously streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param str parent_call_sid: Only include calls spawned by calls with this SID. :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -1035,7 +1903,7 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page( + page = await self.page_async( to=to, from_=from_, parent_call_sid=parent_call_sid, @@ -1049,9 +1917,9 @@ def stream( page_size=limits["page_size"], ) - return self._version.stream(page, limits["limit"]) + return self._version.stream_async(page, limits["limit"]) - async def stream_async( + def stream_with_http_info( self, to: Union[str, object] = values.unset, from_: Union[str, object] = values.unset, @@ -1065,23 +1933,21 @@ async def stream_async( end_time_after: Union[datetime, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, - ) -> AsyncIterator[CallInstance]: + ) -> tuple: """ - Asynchronously streams CallInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Streams CallInstance and returns headers from first page + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param str parent_call_sid: Only include calls spawned by calls with this SID. :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -1089,10 +1955,10 @@ async def stream_async( but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results + :returns: tuple of (generator, status_code, headers) where generator yields instances """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async( + page_response = self.page_with_http_info( to=to, from_=from_, parent_call_sid=parent_call_sid, @@ -1106,7 +1972,64 @@ async def stream_async( page_size=limits["page_size"], ) - return self._version.stream_async(page, limits["limit"]) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CallInstance and returns headers from first page + + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) def list( self, @@ -1132,12 +2055,12 @@ def list( :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param str parent_call_sid: Only include calls spawned by calls with this SID. :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -1147,6 +2070,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( to=to, @@ -1188,12 +2112,12 @@ async def list_async( :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param str parent_call_sid: Only include calls spawned by calls with this SID. :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -1203,6 +2127,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1221,6 +2146,116 @@ async def list_async( ) ] + def list_with_http_info( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CallInstance and returns headers from first page + + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CallInstance and returns headers from first page + + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, to: Union[str, object] = values.unset, @@ -1245,12 +2280,12 @@ def page( :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param parent_call_sid: Only include calls spawned by calls with this SID. :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1282,7 +2317,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CallPage(self._version, response, self._solution) + return CallPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1308,12 +2343,12 @@ async def page_async( :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param parent_call_sid: Only include calls spawned by calls with this SID. :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1345,7 +2380,137 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CallPage(self._version, response, self._solution) + return CallPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CallPage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CallPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CallPage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CallPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CallPage: """ @@ -1357,7 +2522,7 @@ def get_page(self, target_url: str) -> CallPage: :returns: Page of CallInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CallPage(self._version, response, self._solution) + return CallPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> CallPage: """ @@ -1369,7 +2534,7 @@ async def get_page_async(self, target_url: str) -> CallPage: :returns: Page of CallInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CallPage(self._version, response, self._solution) + return CallPage(self._version, response, solution=self._solution) def get(self, sid: str) -> CallContext: """ diff --git a/twilio/rest/api/v2010/account/call/event.py b/twilio/rest/api/v2010/account/call/event.py index 80eb8aa8ba..96f3eae3bf 100644 --- a/twilio/rest/api/v2010/account/call/event.py +++ b/twilio/rest/api/v2010/account/call/event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, @@ -146,6 +148,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -165,6 +217,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -191,6 +244,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -199,6 +253,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -230,7 +334,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -263,7 +367,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EventPage: """ @@ -275,7 +449,7 @@ def get_page(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EventPage: """ @@ -287,7 +461,7 @@ async def get_page_async(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/call/notification.py b/twilio/rest/api/v2010/account/call/notification.py index fd9e8c0d00..bed0f202c0 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -119,6 +121,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,20 +174,30 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) - def fetch(self) -> NotificationInstance: + def _fetch(self) -> tuple: """ - Fetch the NotificationInstance - + Internal helper for fetch operation - :returns: The fetched NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + :returns: The fetched NotificationInstance + """ + payload, _, _ = self._fetch() return NotificationInstance( self._version, payload, @@ -176,22 +206,47 @@ def fetch(self) -> NotificationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> NotificationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NotificationInstance + Fetch the NotificationInstance and return response metadata - :returns: The fetched NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = await self._fetch_async() return NotificationInstance( self._version, payload, @@ -200,6 +255,23 @@ async def fetch_async(self) -> NotificationInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -218,6 +290,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, @@ -336,6 +409,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, log: Union[int, object] = values.unset, @@ -363,6 +512,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -401,6 +551,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -413,6 +564,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, log: Union[int, object] = values.unset, @@ -456,7 +681,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -501,7 +726,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> NotificationPage: """ @@ -513,7 +832,7 @@ def get_page(self, target_url: str) -> NotificationPage: :returns: Page of NotificationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> NotificationPage: """ @@ -525,7 +844,7 @@ async def get_page_async(self, target_url: str) -> NotificationPage: :returns: Page of NotificationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> NotificationContext: """ diff --git a/twilio/rest/api/v2010/account/call/payment.py b/twilio/rest/api/v2010/account/call/payment.py index 0f91860987..1d203e8521 100644 --- a/twilio/rest/api/v2010/account/call/payment.py +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,6 +36,10 @@ class Capture(object): POSTAL_CODE = "postal-code" BANK_ROUTING_NUMBER = "bank-routing-number" BANK_ACCOUNT_NUMBER = "bank-account-number" + PAYMENT_CARD_NUMBER_MATCHER = "payment-card-number-matcher" + EXPIRATION_DATE_MATCHER = "expiration-date-matcher" + SECURITY_CODE_MATCHER = "security-code-matcher" + POSTAL_CODE_MATCHER = "postal-code-matcher" class PaymentMethod(object): CREDIT_CARD = "credit-card" @@ -84,6 +89,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[PaymentContext] = None @property @@ -151,6 +157,54 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the PaymentInstance with HTTP info + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + async def update_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PaymentInstance with HTTP info + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -186,22 +240,18 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) - def update( + def _update( self, idempotency_key: str, status_callback: str, capture: Union["PaymentInstance.Capture", object] = values.unset, status: Union["PaymentInstance.Status", object] = values.unset, - ) -> PaymentInstance: + ) -> tuple: """ - Update the PaymentInstance + Internal helper for update operation - :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. - :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. - :param capture: - :param status: - - :returns: The updated PaymentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -218,10 +268,33 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + payload, _, _ = self._update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) return PaymentInstance( self._version, payload, @@ -230,22 +303,50 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, idempotency_key: str, status_callback: str, capture: Union["PaymentInstance.Capture", object] = values.unset, status: Union["PaymentInstance.Status", object] = values.unset, - ) -> PaymentInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PaymentInstance + Update the PaymentInstance and return response metadata :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. :param capture: :param status: - :returns: The updated PaymentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -262,10 +363,33 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronous coroutine to update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + payload, _, _ = await self._update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) return PaymentInstance( self._version, payload, @@ -274,6 +398,38 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PaymentInstance and return response metadata + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -306,7 +462,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( self, idempotency_key: str, status_callback: str, @@ -326,28 +482,14 @@ def create( timeout: Union[int, object] = values.unset, token_type: Union["PaymentInstance.TokenType", object] = values.unset, valid_card_types: Union[str, object] = values.unset, - ) -> PaymentInstance: + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: """ - Create the PaymentInstance - - :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. - :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) - :param bank_account_type: - :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. - :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. - :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. - :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. - :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. - :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). - :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. - :param payment_method: - :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. - :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. - :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. - :param token_type: - :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + Internal helper for create operation - :returns: The created PaymentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,6 +510,8 @@ def create( "Timeout": timeout, "TokenType": token_type, "ValidCardTypes": valid_card_types, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -376,10 +520,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: The created PaymentInstance + """ + payload, _, _ = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) return PaymentInstance( self._version, payload, @@ -387,7 +598,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, idempotency_key: str, status_callback: str, @@ -407,9 +618,11 @@ async def create_async( timeout: Union[int, object] = values.unset, token_type: Union["PaymentInstance.TokenType", object] = values.unset, valid_card_types: Union[str, object] = values.unset, - ) -> PaymentInstance: + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the PaymentInstance + Create the PaymentInstance and return response metadata :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) @@ -427,8 +640,67 @@ async def create_async( :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. :param token_type: :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. - :returns: The created PaymentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -449,6 +721,8 @@ async def create_async( "Timeout": timeout, "TokenType": token_type, "ValidCardTypes": valid_card_types, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -457,10 +731,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronously create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: The created PaymentInstance + """ + payload, _, _ = await self._create_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) return PaymentInstance( self._version, payload, @@ -468,6 +809,81 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PaymentInstance and return response metadata + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> PaymentContext: """ Constructs a PaymentContext diff --git a/twilio/rest/api/v2010/account/call/recording.py b/twilio/rest/api/v2010/account/call/recording.py index 5b93ec6c95..1e17481856 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -104,6 +105,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -141,6 +143,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -159,6 +179,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "RecordingInstance.Status", @@ -195,6 +233,42 @@ async def update_async( pause_behavior=pause_behavior, ) + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + pause_behavior=pause_behavior, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -230,6 +304,20 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -237,10 +325,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -249,27 +359,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RecordingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RecordingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() return RecordingInstance( self._version, payload, @@ -278,22 +404,47 @@ def fetch(self) -> RecordingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RecordingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() return RecordingInstance( self._version, payload, @@ -302,18 +453,33 @@ async def fetch_async(self) -> RecordingInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: "RecordingInstance.Status", pause_behavior: Union[str, object] = values.unset, - ) -> RecordingInstance: + ) -> tuple: """ - Update the RecordingInstance - - :param status: - :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + Internal helper for update operation - :returns: The updated RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -328,10 +494,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + payload, _, _ = self._update(status=status, pause_behavior=pause_behavior) return RecordingInstance( self._version, payload, @@ -340,18 +520,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "RecordingInstance.Status", pause_behavior: Union[str, object] = values.unset, - ) -> RecordingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the RecordingInstance + Update the RecordingInstance and return response metadata :param status: :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. - :returns: The updated RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -366,10 +569,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + payload, _, _ = await self._update_async( + status=status, pause_behavior=pause_behavior + ) return RecordingInstance( self._version, payload, @@ -378,6 +597,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -396,6 +640,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -434,7 +679,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( self, recording_status_callback_event: Union[List[str], object] = values.unset, recording_status_callback: Union[str, object] = values.unset, @@ -442,18 +687,13 @@ def create( trim: Union[str, object] = values.unset, recording_channels: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, - ) -> RecordingInstance: + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: """ - Create the RecordingInstance + Internal helper for create operation - :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. - :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). - :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. - :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. - :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. - :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. - - :returns: The created RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -466,6 +706,7 @@ def create( "Trim": trim, "RecordingChannels": recording_channels, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -474,10 +715,42 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: The created RecordingInstance + """ + payload, _, _ = self._create( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) return RecordingInstance( self._version, payload, @@ -485,7 +758,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, recording_status_callback_event: Union[List[str], object] = values.unset, recording_status_callback: Union[str, object] = values.unset, @@ -493,9 +766,10 @@ async def create_async( trim: Union[str, object] = values.unset, recording_channels: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, - ) -> RecordingInstance: + recording_configuration_id: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the RecordingInstance + Create the RecordingInstance and return response metadata :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). @@ -503,8 +777,42 @@ async def create_async( :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The created RecordingInstance + async def _create_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -517,6 +825,7 @@ async def create_async( "Trim": trim, "RecordingChannels": recording_channels, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -525,10 +834,42 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronously create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: The created RecordingInstance + """ + payload, _, _ = await self._create_async( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) return RecordingInstance( self._version, payload, @@ -536,6 +877,46 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RecordingInstance and return response metadata + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, date_created: Union[date, object] = values.unset, @@ -608,6 +989,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created: Union[date, object] = values.unset, @@ -633,6 +1084,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -668,6 +1120,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -679,6 +1132,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created: Union[date, object] = values.unset, @@ -719,7 +1240,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -761,7 +1282,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RecordingPage: """ @@ -773,7 +1382,7 @@ def get_page(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RecordingPage: """ @@ -785,7 +1394,7 @@ async def get_page_async(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RecordingContext: """ diff --git a/twilio/rest/api/v2010/account/call/siprec.py b/twilio/rest/api/v2010/account/call/siprec.py index d808331c64..30ffea6d94 100644 --- a/twilio/rest/api/v2010/account/call/siprec.py +++ b/twilio/rest/api/v2010/account/call/siprec.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[SiprecContext] = None @property @@ -115,6 +117,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,13 +178,12 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): **self._solution ) - def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: + def _update(self, status: "SiprecInstance.UpdateStatus") -> tuple: """ - Update the SiprecInstance - - :param status: + Internal helper for update operation - :returns: The updated SiprecInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -168,10 +197,19 @@ def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = self._update(status=status) return SiprecInstance( self._version, payload, @@ -180,15 +218,32 @@ def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "SiprecInstance.UpdateStatus" - ) -> SiprecInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SiprecInstance + Update the SiprecInstance and return response metadata :param status: - :returns: The updated SiprecInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "SiprecInstance.UpdateStatus") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -202,10 +257,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> SiprecInstance: + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = await self._update_async(status=status) return SiprecInstance( self._version, payload, @@ -214,6 +280,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SiprecInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,7 +332,2122 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + payload, _, _ = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the SiprecInstance and return response metadata + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( self, name: Union[str, object] = values.unset, connector_name: Union[str, object] = values.unset, @@ -453,7 +2654,7 @@ def create( parameter99_value: Union[str, object] = values.unset, ) -> SiprecInstance: """ - Create the SiprecInstance + Asynchronously create the SiprecInstance :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. @@ -627,258 +2828,245 @@ def create( :param parameter83_name: Parameter name :param parameter83_value: Parameter value :param parameter84_name: Parameter name - :param parameter84_value: Parameter value - :param parameter85_name: Parameter name - :param parameter85_value: Parameter value - :param parameter86_name: Parameter name - :param parameter86_value: Parameter value - :param parameter87_name: Parameter name - :param parameter87_value: Parameter value - :param parameter88_name: Parameter name - :param parameter88_value: Parameter value - :param parameter89_name: Parameter name - :param parameter89_value: Parameter value - :param parameter90_name: Parameter name - :param parameter90_value: Parameter value - :param parameter91_name: Parameter name - :param parameter91_value: Parameter value - :param parameter92_name: Parameter name - :param parameter92_value: Parameter value - :param parameter93_name: Parameter name - :param parameter93_value: Parameter value - :param parameter94_name: Parameter name - :param parameter94_value: Parameter value - :param parameter95_name: Parameter name - :param parameter95_value: Parameter value - :param parameter96_name: Parameter name - :param parameter96_value: Parameter value - :param parameter97_name: Parameter name - :param parameter97_value: Parameter value - :param parameter98_name: Parameter name - :param parameter98_value: Parameter value - :param parameter99_name: Parameter name - :param parameter99_value: Parameter value - - :returns: The created SiprecInstance - """ - - data = values.of( - { - "Name": name, - "ConnectorName": connector_name, - "Track": track, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Parameter1.Name": parameter1_name, - "Parameter1.Value": parameter1_value, - "Parameter2.Name": parameter2_name, - "Parameter2.Value": parameter2_value, - "Parameter3.Name": parameter3_name, - "Parameter3.Value": parameter3_value, - "Parameter4.Name": parameter4_name, - "Parameter4.Value": parameter4_value, - "Parameter5.Name": parameter5_name, - "Parameter5.Value": parameter5_value, - "Parameter6.Name": parameter6_name, - "Parameter6.Value": parameter6_value, - "Parameter7.Name": parameter7_name, - "Parameter7.Value": parameter7_value, - "Parameter8.Name": parameter8_name, - "Parameter8.Value": parameter8_value, - "Parameter9.Name": parameter9_name, - "Parameter9.Value": parameter9_value, - "Parameter10.Name": parameter10_name, - "Parameter10.Value": parameter10_value, - "Parameter11.Name": parameter11_name, - "Parameter11.Value": parameter11_value, - "Parameter12.Name": parameter12_name, - "Parameter12.Value": parameter12_value, - "Parameter13.Name": parameter13_name, - "Parameter13.Value": parameter13_value, - "Parameter14.Name": parameter14_name, - "Parameter14.Value": parameter14_value, - "Parameter15.Name": parameter15_name, - "Parameter15.Value": parameter15_value, - "Parameter16.Name": parameter16_name, - "Parameter16.Value": parameter16_value, - "Parameter17.Name": parameter17_name, - "Parameter17.Value": parameter17_value, - "Parameter18.Name": parameter18_name, - "Parameter18.Value": parameter18_value, - "Parameter19.Name": parameter19_name, - "Parameter19.Value": parameter19_value, - "Parameter20.Name": parameter20_name, - "Parameter20.Value": parameter20_value, - "Parameter21.Name": parameter21_name, - "Parameter21.Value": parameter21_value, - "Parameter22.Name": parameter22_name, - "Parameter22.Value": parameter22_value, - "Parameter23.Name": parameter23_name, - "Parameter23.Value": parameter23_value, - "Parameter24.Name": parameter24_name, - "Parameter24.Value": parameter24_value, - "Parameter25.Name": parameter25_name, - "Parameter25.Value": parameter25_value, - "Parameter26.Name": parameter26_name, - "Parameter26.Value": parameter26_value, - "Parameter27.Name": parameter27_name, - "Parameter27.Value": parameter27_value, - "Parameter28.Name": parameter28_name, - "Parameter28.Value": parameter28_value, - "Parameter29.Name": parameter29_name, - "Parameter29.Value": parameter29_value, - "Parameter30.Name": parameter30_name, - "Parameter30.Value": parameter30_value, - "Parameter31.Name": parameter31_name, - "Parameter31.Value": parameter31_value, - "Parameter32.Name": parameter32_name, - "Parameter32.Value": parameter32_value, - "Parameter33.Name": parameter33_name, - "Parameter33.Value": parameter33_value, - "Parameter34.Name": parameter34_name, - "Parameter34.Value": parameter34_value, - "Parameter35.Name": parameter35_name, - "Parameter35.Value": parameter35_value, - "Parameter36.Name": parameter36_name, - "Parameter36.Value": parameter36_value, - "Parameter37.Name": parameter37_name, - "Parameter37.Value": parameter37_value, - "Parameter38.Name": parameter38_name, - "Parameter38.Value": parameter38_value, - "Parameter39.Name": parameter39_name, - "Parameter39.Value": parameter39_value, - "Parameter40.Name": parameter40_name, - "Parameter40.Value": parameter40_value, - "Parameter41.Name": parameter41_name, - "Parameter41.Value": parameter41_value, - "Parameter42.Name": parameter42_name, - "Parameter42.Value": parameter42_value, - "Parameter43.Name": parameter43_name, - "Parameter43.Value": parameter43_value, - "Parameter44.Name": parameter44_name, - "Parameter44.Value": parameter44_value, - "Parameter45.Name": parameter45_name, - "Parameter45.Value": parameter45_value, - "Parameter46.Name": parameter46_name, - "Parameter46.Value": parameter46_value, - "Parameter47.Name": parameter47_name, - "Parameter47.Value": parameter47_value, - "Parameter48.Name": parameter48_name, - "Parameter48.Value": parameter48_value, - "Parameter49.Name": parameter49_name, - "Parameter49.Value": parameter49_value, - "Parameter50.Name": parameter50_name, - "Parameter50.Value": parameter50_value, - "Parameter51.Name": parameter51_name, - "Parameter51.Value": parameter51_value, - "Parameter52.Name": parameter52_name, - "Parameter52.Value": parameter52_value, - "Parameter53.Name": parameter53_name, - "Parameter53.Value": parameter53_value, - "Parameter54.Name": parameter54_name, - "Parameter54.Value": parameter54_value, - "Parameter55.Name": parameter55_name, - "Parameter55.Value": parameter55_value, - "Parameter56.Name": parameter56_name, - "Parameter56.Value": parameter56_value, - "Parameter57.Name": parameter57_name, - "Parameter57.Value": parameter57_value, - "Parameter58.Name": parameter58_name, - "Parameter58.Value": parameter58_value, - "Parameter59.Name": parameter59_name, - "Parameter59.Value": parameter59_value, - "Parameter60.Name": parameter60_name, - "Parameter60.Value": parameter60_value, - "Parameter61.Name": parameter61_name, - "Parameter61.Value": parameter61_value, - "Parameter62.Name": parameter62_name, - "Parameter62.Value": parameter62_value, - "Parameter63.Name": parameter63_name, - "Parameter63.Value": parameter63_value, - "Parameter64.Name": parameter64_name, - "Parameter64.Value": parameter64_value, - "Parameter65.Name": parameter65_name, - "Parameter65.Value": parameter65_value, - "Parameter66.Name": parameter66_name, - "Parameter66.Value": parameter66_value, - "Parameter67.Name": parameter67_name, - "Parameter67.Value": parameter67_value, - "Parameter68.Name": parameter68_name, - "Parameter68.Value": parameter68_value, - "Parameter69.Name": parameter69_name, - "Parameter69.Value": parameter69_value, - "Parameter70.Name": parameter70_name, - "Parameter70.Value": parameter70_value, - "Parameter71.Name": parameter71_name, - "Parameter71.Value": parameter71_value, - "Parameter72.Name": parameter72_name, - "Parameter72.Value": parameter72_value, - "Parameter73.Name": parameter73_name, - "Parameter73.Value": parameter73_value, - "Parameter74.Name": parameter74_name, - "Parameter74.Value": parameter74_value, - "Parameter75.Name": parameter75_name, - "Parameter75.Value": parameter75_value, - "Parameter76.Name": parameter76_name, - "Parameter76.Value": parameter76_value, - "Parameter77.Name": parameter77_name, - "Parameter77.Value": parameter77_value, - "Parameter78.Name": parameter78_name, - "Parameter78.Value": parameter78_value, - "Parameter79.Name": parameter79_name, - "Parameter79.Value": parameter79_value, - "Parameter80.Name": parameter80_name, - "Parameter80.Value": parameter80_value, - "Parameter81.Name": parameter81_name, - "Parameter81.Value": parameter81_value, - "Parameter82.Name": parameter82_name, - "Parameter82.Value": parameter82_value, - "Parameter83.Name": parameter83_name, - "Parameter83.Value": parameter83_value, - "Parameter84.Name": parameter84_name, - "Parameter84.Value": parameter84_value, - "Parameter85.Name": parameter85_name, - "Parameter85.Value": parameter85_value, - "Parameter86.Name": parameter86_name, - "Parameter86.Value": parameter86_value, - "Parameter87.Name": parameter87_name, - "Parameter87.Value": parameter87_value, - "Parameter88.Name": parameter88_name, - "Parameter88.Value": parameter88_value, - "Parameter89.Name": parameter89_name, - "Parameter89.Value": parameter89_value, - "Parameter90.Name": parameter90_name, - "Parameter90.Value": parameter90_value, - "Parameter91.Name": parameter91_name, - "Parameter91.Value": parameter91_value, - "Parameter92.Name": parameter92_name, - "Parameter92.Value": parameter92_value, - "Parameter93.Name": parameter93_name, - "Parameter93.Value": parameter93_value, - "Parameter94.Name": parameter94_name, - "Parameter94.Value": parameter94_value, - "Parameter95.Name": parameter95_name, - "Parameter95.Value": parameter95_value, - "Parameter96.Name": parameter96_name, - "Parameter96.Value": parameter96_value, - "Parameter97.Name": parameter97_name, - "Parameter97.Value": parameter97_value, - "Parameter98.Name": parameter98_name, - "Parameter98.Value": parameter98_value, - "Parameter99.Name": parameter99_name, - "Parameter99.Value": parameter99_value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + :returns: The created SiprecInstance + """ + payload, _, _ = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - return SiprecInstance( self._version, payload, @@ -886,7 +3074,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + async def create_with_http_info_async( self, name: Union[str, object] = values.unset, connector_name: Union[str, object] = values.unset, @@ -1091,9 +3279,9 @@ async def create_async( parameter98_value: Union[str, object] = values.unset, parameter99_name: Union[str, object] = values.unset, parameter99_value: Union[str, object] = values.unset, - ) -> SiprecInstance: + ) -> ApiResponse: """ - Asynchronously create the SiprecInstance + Asynchronously create the SiprecInstance and return response metadata :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. @@ -1299,232 +3487,220 @@ async def create_async( :param parameter99_name: Parameter name :param parameter99_value: Parameter value - :returns: The created SiprecInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "Name": name, - "ConnectorName": connector_name, - "Track": track, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Parameter1.Name": parameter1_name, - "Parameter1.Value": parameter1_value, - "Parameter2.Name": parameter2_name, - "Parameter2.Value": parameter2_value, - "Parameter3.Name": parameter3_name, - "Parameter3.Value": parameter3_value, - "Parameter4.Name": parameter4_name, - "Parameter4.Value": parameter4_value, - "Parameter5.Name": parameter5_name, - "Parameter5.Value": parameter5_value, - "Parameter6.Name": parameter6_name, - "Parameter6.Value": parameter6_value, - "Parameter7.Name": parameter7_name, - "Parameter7.Value": parameter7_value, - "Parameter8.Name": parameter8_name, - "Parameter8.Value": parameter8_value, - "Parameter9.Name": parameter9_name, - "Parameter9.Value": parameter9_value, - "Parameter10.Name": parameter10_name, - "Parameter10.Value": parameter10_value, - "Parameter11.Name": parameter11_name, - "Parameter11.Value": parameter11_value, - "Parameter12.Name": parameter12_name, - "Parameter12.Value": parameter12_value, - "Parameter13.Name": parameter13_name, - "Parameter13.Value": parameter13_value, - "Parameter14.Name": parameter14_name, - "Parameter14.Value": parameter14_value, - "Parameter15.Name": parameter15_name, - "Parameter15.Value": parameter15_value, - "Parameter16.Name": parameter16_name, - "Parameter16.Value": parameter16_value, - "Parameter17.Name": parameter17_name, - "Parameter17.Value": parameter17_value, - "Parameter18.Name": parameter18_name, - "Parameter18.Value": parameter18_value, - "Parameter19.Name": parameter19_name, - "Parameter19.Value": parameter19_value, - "Parameter20.Name": parameter20_name, - "Parameter20.Value": parameter20_value, - "Parameter21.Name": parameter21_name, - "Parameter21.Value": parameter21_value, - "Parameter22.Name": parameter22_name, - "Parameter22.Value": parameter22_value, - "Parameter23.Name": parameter23_name, - "Parameter23.Value": parameter23_value, - "Parameter24.Name": parameter24_name, - "Parameter24.Value": parameter24_value, - "Parameter25.Name": parameter25_name, - "Parameter25.Value": parameter25_value, - "Parameter26.Name": parameter26_name, - "Parameter26.Value": parameter26_value, - "Parameter27.Name": parameter27_name, - "Parameter27.Value": parameter27_value, - "Parameter28.Name": parameter28_name, - "Parameter28.Value": parameter28_value, - "Parameter29.Name": parameter29_name, - "Parameter29.Value": parameter29_value, - "Parameter30.Name": parameter30_name, - "Parameter30.Value": parameter30_value, - "Parameter31.Name": parameter31_name, - "Parameter31.Value": parameter31_value, - "Parameter32.Name": parameter32_name, - "Parameter32.Value": parameter32_value, - "Parameter33.Name": parameter33_name, - "Parameter33.Value": parameter33_value, - "Parameter34.Name": parameter34_name, - "Parameter34.Value": parameter34_value, - "Parameter35.Name": parameter35_name, - "Parameter35.Value": parameter35_value, - "Parameter36.Name": parameter36_name, - "Parameter36.Value": parameter36_value, - "Parameter37.Name": parameter37_name, - "Parameter37.Value": parameter37_value, - "Parameter38.Name": parameter38_name, - "Parameter38.Value": parameter38_value, - "Parameter39.Name": parameter39_name, - "Parameter39.Value": parameter39_value, - "Parameter40.Name": parameter40_name, - "Parameter40.Value": parameter40_value, - "Parameter41.Name": parameter41_name, - "Parameter41.Value": parameter41_value, - "Parameter42.Name": parameter42_name, - "Parameter42.Value": parameter42_value, - "Parameter43.Name": parameter43_name, - "Parameter43.Value": parameter43_value, - "Parameter44.Name": parameter44_name, - "Parameter44.Value": parameter44_value, - "Parameter45.Name": parameter45_name, - "Parameter45.Value": parameter45_value, - "Parameter46.Name": parameter46_name, - "Parameter46.Value": parameter46_value, - "Parameter47.Name": parameter47_name, - "Parameter47.Value": parameter47_value, - "Parameter48.Name": parameter48_name, - "Parameter48.Value": parameter48_value, - "Parameter49.Name": parameter49_name, - "Parameter49.Value": parameter49_value, - "Parameter50.Name": parameter50_name, - "Parameter50.Value": parameter50_value, - "Parameter51.Name": parameter51_name, - "Parameter51.Value": parameter51_value, - "Parameter52.Name": parameter52_name, - "Parameter52.Value": parameter52_value, - "Parameter53.Name": parameter53_name, - "Parameter53.Value": parameter53_value, - "Parameter54.Name": parameter54_name, - "Parameter54.Value": parameter54_value, - "Parameter55.Name": parameter55_name, - "Parameter55.Value": parameter55_value, - "Parameter56.Name": parameter56_name, - "Parameter56.Value": parameter56_value, - "Parameter57.Name": parameter57_name, - "Parameter57.Value": parameter57_value, - "Parameter58.Name": parameter58_name, - "Parameter58.Value": parameter58_value, - "Parameter59.Name": parameter59_name, - "Parameter59.Value": parameter59_value, - "Parameter60.Name": parameter60_name, - "Parameter60.Value": parameter60_value, - "Parameter61.Name": parameter61_name, - "Parameter61.Value": parameter61_value, - "Parameter62.Name": parameter62_name, - "Parameter62.Value": parameter62_value, - "Parameter63.Name": parameter63_name, - "Parameter63.Value": parameter63_value, - "Parameter64.Name": parameter64_name, - "Parameter64.Value": parameter64_value, - "Parameter65.Name": parameter65_name, - "Parameter65.Value": parameter65_value, - "Parameter66.Name": parameter66_name, - "Parameter66.Value": parameter66_value, - "Parameter67.Name": parameter67_name, - "Parameter67.Value": parameter67_value, - "Parameter68.Name": parameter68_name, - "Parameter68.Value": parameter68_value, - "Parameter69.Name": parameter69_name, - "Parameter69.Value": parameter69_value, - "Parameter70.Name": parameter70_name, - "Parameter70.Value": parameter70_value, - "Parameter71.Name": parameter71_name, - "Parameter71.Value": parameter71_value, - "Parameter72.Name": parameter72_name, - "Parameter72.Value": parameter72_value, - "Parameter73.Name": parameter73_name, - "Parameter73.Value": parameter73_value, - "Parameter74.Name": parameter74_name, - "Parameter74.Value": parameter74_value, - "Parameter75.Name": parameter75_name, - "Parameter75.Value": parameter75_value, - "Parameter76.Name": parameter76_name, - "Parameter76.Value": parameter76_value, - "Parameter77.Name": parameter77_name, - "Parameter77.Value": parameter77_value, - "Parameter78.Name": parameter78_name, - "Parameter78.Value": parameter78_value, - "Parameter79.Name": parameter79_name, - "Parameter79.Value": parameter79_value, - "Parameter80.Name": parameter80_name, - "Parameter80.Value": parameter80_value, - "Parameter81.Name": parameter81_name, - "Parameter81.Value": parameter81_value, - "Parameter82.Name": parameter82_name, - "Parameter82.Value": parameter82_value, - "Parameter83.Name": parameter83_name, - "Parameter83.Value": parameter83_value, - "Parameter84.Name": parameter84_name, - "Parameter84.Value": parameter84_value, - "Parameter85.Name": parameter85_name, - "Parameter85.Value": parameter85_value, - "Parameter86.Name": parameter86_name, - "Parameter86.Value": parameter86_value, - "Parameter87.Name": parameter87_name, - "Parameter87.Value": parameter87_value, - "Parameter88.Name": parameter88_name, - "Parameter88.Value": parameter88_value, - "Parameter89.Name": parameter89_name, - "Parameter89.Value": parameter89_value, - "Parameter90.Name": parameter90_name, - "Parameter90.Value": parameter90_value, - "Parameter91.Name": parameter91_name, - "Parameter91.Value": parameter91_value, - "Parameter92.Name": parameter92_name, - "Parameter92.Value": parameter92_value, - "Parameter93.Name": parameter93_name, - "Parameter93.Value": parameter93_value, - "Parameter94.Name": parameter94_name, - "Parameter94.Value": parameter94_value, - "Parameter95.Name": parameter95_name, - "Parameter95.Value": parameter95_value, - "Parameter96.Name": parameter96_name, - "Parameter96.Value": parameter96_value, - "Parameter97.Name": parameter97_name, - "Parameter97.Value": parameter97_value, - "Parameter98.Name": parameter98_name, - "Parameter98.Value": parameter98_value, - "Parameter99.Name": parameter99_name, - "Parameter99.Value": parameter99_value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - - return SiprecInstance( + instance = SiprecInstance( self._version, payload, account_sid=self._solution["account_sid"], call_sid=self._solution["call_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def get(self, sid: str) -> SiprecContext: """ diff --git a/twilio/rest/api/v2010/account/call/stream.py b/twilio/rest/api/v2010/account/call/stream.py index 1a506e6684..99338e0663 100644 --- a/twilio/rest/api/v2010/account/call/stream.py +++ b/twilio/rest/api/v2010/account/call/stream.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[StreamContext] = None @property @@ -115,6 +117,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,13 +180,12 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) - def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: + def _update(self, status: "StreamInstance.UpdateStatus") -> tuple: """ - Update the StreamInstance - - :param status: + Internal helper for update operation - :returns: The updated StreamInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -170,10 +199,19 @@ def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = self._update(status=status) return StreamInstance( self._version, payload, @@ -182,15 +220,32 @@ def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "StreamInstance.UpdateStatus" - ) -> StreamInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the StreamInstance + Update the StreamInstance and return response metadata :param status: - :returns: The updated StreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "StreamInstance.UpdateStatus") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -204,10 +259,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> StreamInstance: + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = await self._update_async(status=status) return StreamInstance( self._version, payload, @@ -216,6 +282,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the StreamInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -248,7 +334,2122 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + payload, _, _ = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the StreamInstance and return response metadata + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( self, url: str, name: Union[str, object] = values.unset, @@ -455,7 +2656,7 @@ def create( parameter99_value: Union[str, object] = values.unset, ) -> StreamInstance: """ - Create the StreamInstance + Asynchronously create the StreamInstance :param url: Relative or absolute URL where WebSocket connection will be established. :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. @@ -629,258 +2830,245 @@ def create( :param parameter83_name: Parameter name :param parameter83_value: Parameter value :param parameter84_name: Parameter name - :param parameter84_value: Parameter value - :param parameter85_name: Parameter name - :param parameter85_value: Parameter value - :param parameter86_name: Parameter name - :param parameter86_value: Parameter value - :param parameter87_name: Parameter name - :param parameter87_value: Parameter value - :param parameter88_name: Parameter name - :param parameter88_value: Parameter value - :param parameter89_name: Parameter name - :param parameter89_value: Parameter value - :param parameter90_name: Parameter name - :param parameter90_value: Parameter value - :param parameter91_name: Parameter name - :param parameter91_value: Parameter value - :param parameter92_name: Parameter name - :param parameter92_value: Parameter value - :param parameter93_name: Parameter name - :param parameter93_value: Parameter value - :param parameter94_name: Parameter name - :param parameter94_value: Parameter value - :param parameter95_name: Parameter name - :param parameter95_value: Parameter value - :param parameter96_name: Parameter name - :param parameter96_value: Parameter value - :param parameter97_name: Parameter name - :param parameter97_value: Parameter value - :param parameter98_name: Parameter name - :param parameter98_value: Parameter value - :param parameter99_name: Parameter name - :param parameter99_value: Parameter value - - :returns: The created StreamInstance - """ - - data = values.of( - { - "Url": url, - "Name": name, - "Track": track, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Parameter1.Name": parameter1_name, - "Parameter1.Value": parameter1_value, - "Parameter2.Name": parameter2_name, - "Parameter2.Value": parameter2_value, - "Parameter3.Name": parameter3_name, - "Parameter3.Value": parameter3_value, - "Parameter4.Name": parameter4_name, - "Parameter4.Value": parameter4_value, - "Parameter5.Name": parameter5_name, - "Parameter5.Value": parameter5_value, - "Parameter6.Name": parameter6_name, - "Parameter6.Value": parameter6_value, - "Parameter7.Name": parameter7_name, - "Parameter7.Value": parameter7_value, - "Parameter8.Name": parameter8_name, - "Parameter8.Value": parameter8_value, - "Parameter9.Name": parameter9_name, - "Parameter9.Value": parameter9_value, - "Parameter10.Name": parameter10_name, - "Parameter10.Value": parameter10_value, - "Parameter11.Name": parameter11_name, - "Parameter11.Value": parameter11_value, - "Parameter12.Name": parameter12_name, - "Parameter12.Value": parameter12_value, - "Parameter13.Name": parameter13_name, - "Parameter13.Value": parameter13_value, - "Parameter14.Name": parameter14_name, - "Parameter14.Value": parameter14_value, - "Parameter15.Name": parameter15_name, - "Parameter15.Value": parameter15_value, - "Parameter16.Name": parameter16_name, - "Parameter16.Value": parameter16_value, - "Parameter17.Name": parameter17_name, - "Parameter17.Value": parameter17_value, - "Parameter18.Name": parameter18_name, - "Parameter18.Value": parameter18_value, - "Parameter19.Name": parameter19_name, - "Parameter19.Value": parameter19_value, - "Parameter20.Name": parameter20_name, - "Parameter20.Value": parameter20_value, - "Parameter21.Name": parameter21_name, - "Parameter21.Value": parameter21_value, - "Parameter22.Name": parameter22_name, - "Parameter22.Value": parameter22_value, - "Parameter23.Name": parameter23_name, - "Parameter23.Value": parameter23_value, - "Parameter24.Name": parameter24_name, - "Parameter24.Value": parameter24_value, - "Parameter25.Name": parameter25_name, - "Parameter25.Value": parameter25_value, - "Parameter26.Name": parameter26_name, - "Parameter26.Value": parameter26_value, - "Parameter27.Name": parameter27_name, - "Parameter27.Value": parameter27_value, - "Parameter28.Name": parameter28_name, - "Parameter28.Value": parameter28_value, - "Parameter29.Name": parameter29_name, - "Parameter29.Value": parameter29_value, - "Parameter30.Name": parameter30_name, - "Parameter30.Value": parameter30_value, - "Parameter31.Name": parameter31_name, - "Parameter31.Value": parameter31_value, - "Parameter32.Name": parameter32_name, - "Parameter32.Value": parameter32_value, - "Parameter33.Name": parameter33_name, - "Parameter33.Value": parameter33_value, - "Parameter34.Name": parameter34_name, - "Parameter34.Value": parameter34_value, - "Parameter35.Name": parameter35_name, - "Parameter35.Value": parameter35_value, - "Parameter36.Name": parameter36_name, - "Parameter36.Value": parameter36_value, - "Parameter37.Name": parameter37_name, - "Parameter37.Value": parameter37_value, - "Parameter38.Name": parameter38_name, - "Parameter38.Value": parameter38_value, - "Parameter39.Name": parameter39_name, - "Parameter39.Value": parameter39_value, - "Parameter40.Name": parameter40_name, - "Parameter40.Value": parameter40_value, - "Parameter41.Name": parameter41_name, - "Parameter41.Value": parameter41_value, - "Parameter42.Name": parameter42_name, - "Parameter42.Value": parameter42_value, - "Parameter43.Name": parameter43_name, - "Parameter43.Value": parameter43_value, - "Parameter44.Name": parameter44_name, - "Parameter44.Value": parameter44_value, - "Parameter45.Name": parameter45_name, - "Parameter45.Value": parameter45_value, - "Parameter46.Name": parameter46_name, - "Parameter46.Value": parameter46_value, - "Parameter47.Name": parameter47_name, - "Parameter47.Value": parameter47_value, - "Parameter48.Name": parameter48_name, - "Parameter48.Value": parameter48_value, - "Parameter49.Name": parameter49_name, - "Parameter49.Value": parameter49_value, - "Parameter50.Name": parameter50_name, - "Parameter50.Value": parameter50_value, - "Parameter51.Name": parameter51_name, - "Parameter51.Value": parameter51_value, - "Parameter52.Name": parameter52_name, - "Parameter52.Value": parameter52_value, - "Parameter53.Name": parameter53_name, - "Parameter53.Value": parameter53_value, - "Parameter54.Name": parameter54_name, - "Parameter54.Value": parameter54_value, - "Parameter55.Name": parameter55_name, - "Parameter55.Value": parameter55_value, - "Parameter56.Name": parameter56_name, - "Parameter56.Value": parameter56_value, - "Parameter57.Name": parameter57_name, - "Parameter57.Value": parameter57_value, - "Parameter58.Name": parameter58_name, - "Parameter58.Value": parameter58_value, - "Parameter59.Name": parameter59_name, - "Parameter59.Value": parameter59_value, - "Parameter60.Name": parameter60_name, - "Parameter60.Value": parameter60_value, - "Parameter61.Name": parameter61_name, - "Parameter61.Value": parameter61_value, - "Parameter62.Name": parameter62_name, - "Parameter62.Value": parameter62_value, - "Parameter63.Name": parameter63_name, - "Parameter63.Value": parameter63_value, - "Parameter64.Name": parameter64_name, - "Parameter64.Value": parameter64_value, - "Parameter65.Name": parameter65_name, - "Parameter65.Value": parameter65_value, - "Parameter66.Name": parameter66_name, - "Parameter66.Value": parameter66_value, - "Parameter67.Name": parameter67_name, - "Parameter67.Value": parameter67_value, - "Parameter68.Name": parameter68_name, - "Parameter68.Value": parameter68_value, - "Parameter69.Name": parameter69_name, - "Parameter69.Value": parameter69_value, - "Parameter70.Name": parameter70_name, - "Parameter70.Value": parameter70_value, - "Parameter71.Name": parameter71_name, - "Parameter71.Value": parameter71_value, - "Parameter72.Name": parameter72_name, - "Parameter72.Value": parameter72_value, - "Parameter73.Name": parameter73_name, - "Parameter73.Value": parameter73_value, - "Parameter74.Name": parameter74_name, - "Parameter74.Value": parameter74_value, - "Parameter75.Name": parameter75_name, - "Parameter75.Value": parameter75_value, - "Parameter76.Name": parameter76_name, - "Parameter76.Value": parameter76_value, - "Parameter77.Name": parameter77_name, - "Parameter77.Value": parameter77_value, - "Parameter78.Name": parameter78_name, - "Parameter78.Value": parameter78_value, - "Parameter79.Name": parameter79_name, - "Parameter79.Value": parameter79_value, - "Parameter80.Name": parameter80_name, - "Parameter80.Value": parameter80_value, - "Parameter81.Name": parameter81_name, - "Parameter81.Value": parameter81_value, - "Parameter82.Name": parameter82_name, - "Parameter82.Value": parameter82_value, - "Parameter83.Name": parameter83_name, - "Parameter83.Value": parameter83_value, - "Parameter84.Name": parameter84_name, - "Parameter84.Value": parameter84_value, - "Parameter85.Name": parameter85_name, - "Parameter85.Value": parameter85_value, - "Parameter86.Name": parameter86_name, - "Parameter86.Value": parameter86_value, - "Parameter87.Name": parameter87_name, - "Parameter87.Value": parameter87_value, - "Parameter88.Name": parameter88_name, - "Parameter88.Value": parameter88_value, - "Parameter89.Name": parameter89_name, - "Parameter89.Value": parameter89_value, - "Parameter90.Name": parameter90_name, - "Parameter90.Value": parameter90_value, - "Parameter91.Name": parameter91_name, - "Parameter91.Value": parameter91_value, - "Parameter92.Name": parameter92_name, - "Parameter92.Value": parameter92_value, - "Parameter93.Name": parameter93_name, - "Parameter93.Value": parameter93_value, - "Parameter94.Name": parameter94_name, - "Parameter94.Value": parameter94_value, - "Parameter95.Name": parameter95_name, - "Parameter95.Value": parameter95_value, - "Parameter96.Name": parameter96_name, - "Parameter96.Value": parameter96_value, - "Parameter97.Name": parameter97_name, - "Parameter97.Value": parameter97_value, - "Parameter98.Name": parameter98_name, - "Parameter98.Value": parameter98_value, - "Parameter99.Name": parameter99_name, - "Parameter99.Value": parameter99_value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + :returns: The created StreamInstance + """ + payload, _, _ = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - return StreamInstance( self._version, payload, @@ -888,7 +3076,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + async def create_with_http_info_async( self, url: str, name: Union[str, object] = values.unset, @@ -1093,9 +3281,9 @@ async def create_async( parameter98_value: Union[str, object] = values.unset, parameter99_name: Union[str, object] = values.unset, parameter99_value: Union[str, object] = values.unset, - ) -> StreamInstance: + ) -> ApiResponse: """ - Asynchronously create the StreamInstance + Asynchronously create the StreamInstance and return response metadata :param url: Relative or absolute URL where WebSocket connection will be established. :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. @@ -1301,232 +3489,220 @@ async def create_async( :param parameter99_name: Parameter name :param parameter99_value: Parameter value - :returns: The created StreamInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "Url": url, - "Name": name, - "Track": track, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Parameter1.Name": parameter1_name, - "Parameter1.Value": parameter1_value, - "Parameter2.Name": parameter2_name, - "Parameter2.Value": parameter2_value, - "Parameter3.Name": parameter3_name, - "Parameter3.Value": parameter3_value, - "Parameter4.Name": parameter4_name, - "Parameter4.Value": parameter4_value, - "Parameter5.Name": parameter5_name, - "Parameter5.Value": parameter5_value, - "Parameter6.Name": parameter6_name, - "Parameter6.Value": parameter6_value, - "Parameter7.Name": parameter7_name, - "Parameter7.Value": parameter7_value, - "Parameter8.Name": parameter8_name, - "Parameter8.Value": parameter8_value, - "Parameter9.Name": parameter9_name, - "Parameter9.Value": parameter9_value, - "Parameter10.Name": parameter10_name, - "Parameter10.Value": parameter10_value, - "Parameter11.Name": parameter11_name, - "Parameter11.Value": parameter11_value, - "Parameter12.Name": parameter12_name, - "Parameter12.Value": parameter12_value, - "Parameter13.Name": parameter13_name, - "Parameter13.Value": parameter13_value, - "Parameter14.Name": parameter14_name, - "Parameter14.Value": parameter14_value, - "Parameter15.Name": parameter15_name, - "Parameter15.Value": parameter15_value, - "Parameter16.Name": parameter16_name, - "Parameter16.Value": parameter16_value, - "Parameter17.Name": parameter17_name, - "Parameter17.Value": parameter17_value, - "Parameter18.Name": parameter18_name, - "Parameter18.Value": parameter18_value, - "Parameter19.Name": parameter19_name, - "Parameter19.Value": parameter19_value, - "Parameter20.Name": parameter20_name, - "Parameter20.Value": parameter20_value, - "Parameter21.Name": parameter21_name, - "Parameter21.Value": parameter21_value, - "Parameter22.Name": parameter22_name, - "Parameter22.Value": parameter22_value, - "Parameter23.Name": parameter23_name, - "Parameter23.Value": parameter23_value, - "Parameter24.Name": parameter24_name, - "Parameter24.Value": parameter24_value, - "Parameter25.Name": parameter25_name, - "Parameter25.Value": parameter25_value, - "Parameter26.Name": parameter26_name, - "Parameter26.Value": parameter26_value, - "Parameter27.Name": parameter27_name, - "Parameter27.Value": parameter27_value, - "Parameter28.Name": parameter28_name, - "Parameter28.Value": parameter28_value, - "Parameter29.Name": parameter29_name, - "Parameter29.Value": parameter29_value, - "Parameter30.Name": parameter30_name, - "Parameter30.Value": parameter30_value, - "Parameter31.Name": parameter31_name, - "Parameter31.Value": parameter31_value, - "Parameter32.Name": parameter32_name, - "Parameter32.Value": parameter32_value, - "Parameter33.Name": parameter33_name, - "Parameter33.Value": parameter33_value, - "Parameter34.Name": parameter34_name, - "Parameter34.Value": parameter34_value, - "Parameter35.Name": parameter35_name, - "Parameter35.Value": parameter35_value, - "Parameter36.Name": parameter36_name, - "Parameter36.Value": parameter36_value, - "Parameter37.Name": parameter37_name, - "Parameter37.Value": parameter37_value, - "Parameter38.Name": parameter38_name, - "Parameter38.Value": parameter38_value, - "Parameter39.Name": parameter39_name, - "Parameter39.Value": parameter39_value, - "Parameter40.Name": parameter40_name, - "Parameter40.Value": parameter40_value, - "Parameter41.Name": parameter41_name, - "Parameter41.Value": parameter41_value, - "Parameter42.Name": parameter42_name, - "Parameter42.Value": parameter42_value, - "Parameter43.Name": parameter43_name, - "Parameter43.Value": parameter43_value, - "Parameter44.Name": parameter44_name, - "Parameter44.Value": parameter44_value, - "Parameter45.Name": parameter45_name, - "Parameter45.Value": parameter45_value, - "Parameter46.Name": parameter46_name, - "Parameter46.Value": parameter46_value, - "Parameter47.Name": parameter47_name, - "Parameter47.Value": parameter47_value, - "Parameter48.Name": parameter48_name, - "Parameter48.Value": parameter48_value, - "Parameter49.Name": parameter49_name, - "Parameter49.Value": parameter49_value, - "Parameter50.Name": parameter50_name, - "Parameter50.Value": parameter50_value, - "Parameter51.Name": parameter51_name, - "Parameter51.Value": parameter51_value, - "Parameter52.Name": parameter52_name, - "Parameter52.Value": parameter52_value, - "Parameter53.Name": parameter53_name, - "Parameter53.Value": parameter53_value, - "Parameter54.Name": parameter54_name, - "Parameter54.Value": parameter54_value, - "Parameter55.Name": parameter55_name, - "Parameter55.Value": parameter55_value, - "Parameter56.Name": parameter56_name, - "Parameter56.Value": parameter56_value, - "Parameter57.Name": parameter57_name, - "Parameter57.Value": parameter57_value, - "Parameter58.Name": parameter58_name, - "Parameter58.Value": parameter58_value, - "Parameter59.Name": parameter59_name, - "Parameter59.Value": parameter59_value, - "Parameter60.Name": parameter60_name, - "Parameter60.Value": parameter60_value, - "Parameter61.Name": parameter61_name, - "Parameter61.Value": parameter61_value, - "Parameter62.Name": parameter62_name, - "Parameter62.Value": parameter62_value, - "Parameter63.Name": parameter63_name, - "Parameter63.Value": parameter63_value, - "Parameter64.Name": parameter64_name, - "Parameter64.Value": parameter64_value, - "Parameter65.Name": parameter65_name, - "Parameter65.Value": parameter65_value, - "Parameter66.Name": parameter66_name, - "Parameter66.Value": parameter66_value, - "Parameter67.Name": parameter67_name, - "Parameter67.Value": parameter67_value, - "Parameter68.Name": parameter68_name, - "Parameter68.Value": parameter68_value, - "Parameter69.Name": parameter69_name, - "Parameter69.Value": parameter69_value, - "Parameter70.Name": parameter70_name, - "Parameter70.Value": parameter70_value, - "Parameter71.Name": parameter71_name, - "Parameter71.Value": parameter71_value, - "Parameter72.Name": parameter72_name, - "Parameter72.Value": parameter72_value, - "Parameter73.Name": parameter73_name, - "Parameter73.Value": parameter73_value, - "Parameter74.Name": parameter74_name, - "Parameter74.Value": parameter74_value, - "Parameter75.Name": parameter75_name, - "Parameter75.Value": parameter75_value, - "Parameter76.Name": parameter76_name, - "Parameter76.Value": parameter76_value, - "Parameter77.Name": parameter77_name, - "Parameter77.Value": parameter77_value, - "Parameter78.Name": parameter78_name, - "Parameter78.Value": parameter78_value, - "Parameter79.Name": parameter79_name, - "Parameter79.Value": parameter79_value, - "Parameter80.Name": parameter80_name, - "Parameter80.Value": parameter80_value, - "Parameter81.Name": parameter81_name, - "Parameter81.Value": parameter81_value, - "Parameter82.Name": parameter82_name, - "Parameter82.Value": parameter82_value, - "Parameter83.Name": parameter83_name, - "Parameter83.Value": parameter83_value, - "Parameter84.Name": parameter84_name, - "Parameter84.Value": parameter84_value, - "Parameter85.Name": parameter85_name, - "Parameter85.Value": parameter85_value, - "Parameter86.Name": parameter86_name, - "Parameter86.Value": parameter86_value, - "Parameter87.Name": parameter87_name, - "Parameter87.Value": parameter87_value, - "Parameter88.Name": parameter88_name, - "Parameter88.Value": parameter88_value, - "Parameter89.Name": parameter89_name, - "Parameter89.Value": parameter89_value, - "Parameter90.Name": parameter90_name, - "Parameter90.Value": parameter90_value, - "Parameter91.Name": parameter91_name, - "Parameter91.Value": parameter91_value, - "Parameter92.Name": parameter92_name, - "Parameter92.Value": parameter92_value, - "Parameter93.Name": parameter93_name, - "Parameter93.Value": parameter93_value, - "Parameter94.Name": parameter94_name, - "Parameter94.Value": parameter94_value, - "Parameter95.Name": parameter95_name, - "Parameter95.Value": parameter95_value, - "Parameter96.Name": parameter96_name, - "Parameter96.Value": parameter96_value, - "Parameter97.Name": parameter97_name, - "Parameter97.Value": parameter97_value, - "Parameter98.Name": parameter98_name, - "Parameter98.Value": parameter98_value, - "Parameter99.Name": parameter99_name, - "Parameter99.Value": parameter99_value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - - return StreamInstance( + instance = StreamInstance( self._version, payload, account_sid=self._solution["account_sid"], call_sid=self._solution["call_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def get(self, sid: str) -> StreamContext: """ diff --git a/twilio/rest/api/v2010/account/call/transcription.py b/twilio/rest/api/v2010/account/call/transcription.py index d64a5507b4..0d56c61ff3 100644 --- a/twilio/rest/api/v2010/account/call/transcription.py +++ b/twilio/rest/api/v2010/account/call/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -117,6 +119,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -152,15 +182,12 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) - def update( - self, status: "TranscriptionInstance.UpdateStatus" - ) -> TranscriptionInstance: + def _update(self, status: "TranscriptionInstance.UpdateStatus") -> tuple: """ - Update the TranscriptionInstance + Internal helper for update operation - :param status: - - :returns: The updated TranscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -174,10 +201,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = self._update(status=status) return TranscriptionInstance( self._version, payload, @@ -186,15 +224,34 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "TranscriptionInstance.UpdateStatus" - ) -> TranscriptionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TranscriptionInstance + Update the TranscriptionInstance and return response metadata :param status: - :returns: The updated TranscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -208,10 +265,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = await self._update_async(status=status) return TranscriptionInstance( self._version, payload, @@ -220,6 +288,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -254,7 +342,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): ) ) - def create( + def _create( self, name: Union[str, object] = values.unset, track: Union["TranscriptionInstance.Track", object] = values.unset, @@ -270,26 +358,16 @@ def create( hints: Union[str, object] = values.unset, enable_automatic_punctuation: Union[bool, object] = values.unset, intelligence_service: Union[str, object] = values.unset, - ) -> TranscriptionInstance: + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> tuple: """ - Create the TranscriptionInstance - - :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. - :param track: - :param status_callback_url: Absolute URL of the status callback. - :param status_callback_method: The http method for the status_callback (one of GET, POST). - :param inbound_track_label: Friendly name given to the Inbound Track - :param outbound_track_label: Friendly name given to the Outbound Track - :param partial_results: Indicates if partial results are going to be sent to the customer - :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format - :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio - :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks - :param speech_model: Recognition model used by the transcription engine, among those supported by the provider - :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. - :param enable_automatic_punctuation: The provider will add punctuation to recognition result - :param intelligence_service: The SID of the [Voice Intelligence Service](https://www.twilio.com/docs/voice/intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + Internal helper for create operation - :returns: The created TranscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,6 +388,10 @@ def create( enable_automatic_punctuation ), "IntelligenceService": intelligence_service, + "ConversationConfiguration": conversation_configuration, + "ConversationId": conversation_id, + "TranscriptionConfigurationId": transcription_configuration_id, + "EnableProviderData": serialize.boolean_to_string(enable_provider_data), } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -318,10 +400,75 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = self._create( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) return TranscriptionInstance( self._version, payload, @@ -329,7 +476,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, name: Union[str, object] = values.unset, track: Union["TranscriptionInstance.Track", object] = values.unset, @@ -345,9 +492,13 @@ async def create_async( hints: Union[str, object] = values.unset, enable_automatic_punctuation: Union[bool, object] = values.unset, intelligence_service: Union[str, object] = values.unset, - ) -> TranscriptionInstance: + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the TranscriptionInstance + Create the TranscriptionInstance and return response metadata :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. :param track: @@ -362,9 +513,68 @@ async def create_async( :param speech_model: Recognition model used by the transcription engine, among those supported by the provider :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. :param enable_automatic_punctuation: The provider will add punctuation to recognition result - :param intelligence_service: The SID of the [Voice Intelligence Service](https://www.twilio.com/docs/voice/intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. - :returns: The created TranscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -385,6 +595,10 @@ async def create_async( enable_automatic_punctuation ), "IntelligenceService": intelligence_service, + "ConversationConfiguration": conversation_configuration, + "ConversationId": conversation_id, + "TranscriptionConfigurationId": transcription_configuration_id, + "EnableProviderData": serialize.boolean_to_string(enable_provider_data), } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -393,10 +607,75 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = await self._create_async( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) return TranscriptionInstance( self._version, payload, @@ -404,6 +683,79 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> TranscriptionContext: """ Constructs a TranscriptionContext diff --git a/twilio/rest/api/v2010/account/call/user_defined_message.py b/twilio/rest/api/v2010/account/call/user_defined_message.py index bc66f8b8e1..d1ed0a91ee 100644 --- a/twilio/rest/api/v2010/account/call/user_defined_message.py +++ b/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,16 +81,14 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): ) ) - def create( + def _create( self, content: str, idempotency_key: Union[str, object] = values.unset - ) -> UserDefinedMessageInstance: + ) -> tuple: """ - Create the UserDefinedMessageInstance - - :param content: The User Defined Message in the form of URL-encoded JSON string. - :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + Internal helper for create operation - :returns: The created UserDefinedMessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -104,10 +103,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + payload, _, _ = self._create(content=content, idempotency_key=idempotency_key) return UserDefinedMessageInstance( self._version, payload, @@ -115,16 +126,36 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, content: str, idempotency_key: Union[str, object] = values.unset - ) -> UserDefinedMessageInstance: + ) -> ApiResponse: """ - Asynchronously create the UserDefinedMessageInstance + Create the UserDefinedMessageInstance and return response metadata :param content: The User Defined Message in the form of URL-encoded JSON string. :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. - :returns: The created UserDefinedMessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content=content, idempotency_key=idempotency_key + ) + instance = UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -139,10 +170,24 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Asynchronously create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + payload, _, _ = await self._create_async( + content=content, idempotency_key=idempotency_key + ) return UserDefinedMessageInstance( self._version, payload, @@ -150,6 +195,28 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the UserDefinedMessageInstance and return response metadata + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content=content, idempotency_key=idempotency_key + ) + instance = UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py index 66923d4b79..eea6263faa 100644 --- a/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py +++ b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[UserDefinedMessageSubscriptionContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -125,6 +145,20 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserDefinedMessageSubscriptionInstance @@ -132,10 +166,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserDefinedMessageSubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -144,12 +200,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -185,20 +247,17 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( self, callback: str, idempotency_key: Union[str, object] = values.unset, method: Union[str, object] = values.unset, - ) -> UserDefinedMessageSubscriptionInstance: + ) -> tuple: """ - Create the UserDefinedMessageSubscriptionInstance - - :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). - :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. - :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + Internal helper for create operation - :returns: The created UserDefinedMessageSubscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -214,10 +273,28 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + payload, _, _ = self._create( + callback=callback, idempotency_key=idempotency_key, method=method + ) return UserDefinedMessageSubscriptionInstance( self._version, payload, @@ -225,20 +302,43 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, callback: str, idempotency_key: Union[str, object] = values.unset, method: Union[str, object] = values.unset, - ) -> UserDefinedMessageSubscriptionInstance: + ) -> ApiResponse: """ - Asynchronously create the UserDefinedMessageSubscriptionInstance + Create the UserDefinedMessageSubscriptionInstance and return response metadata :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. - :returns: The created UserDefinedMessageSubscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback=callback, idempotency_key=idempotency_key, method=method + ) + instance = UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -254,10 +354,28 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Asynchronously create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + payload, _, _ = await self._create_async( + callback=callback, idempotency_key=idempotency_key, method=method + ) return UserDefinedMessageSubscriptionInstance( self._version, payload, @@ -265,6 +383,32 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserDefinedMessageSubscriptionInstance and return response metadata + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback=callback, idempotency_key=idempotency_key, method=method + ) + instance = UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> UserDefinedMessageSubscriptionContext: """ Constructs a UserDefinedMessageSubscriptionContext diff --git a/twilio/rest/api/v2010/account/conference/__init__.py b/twilio/rest/api/v2010/account/conference/__init__.py index 1ff3289a6c..9edc8ce213 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,7 +52,7 @@ class UpdateStatus(object): :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar api_version: The API version used to create this conference. :ivar friendly_name: A string that you assigned to describe this conference room. Maximum length is 128 characters. - :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. + :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. :ivar sid: The unique, Twilio-provided string used to identify this Conference resource. :ivar status: :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. @@ -96,6 +97,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ConferenceContext] = None @property @@ -132,6 +134,24 @@ async def fetch_async(self) -> "ConferenceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, @@ -174,6 +194,48 @@ async def update_async( announce_method=announce_method, ) + def update_with_http_info( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConferenceInstance with HTTP info + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + async def update_with_http_info_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConferenceInstance with HTTP info + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + @property def participants(self) -> ParticipantList: """ @@ -222,20 +284,30 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._participants: Optional[ParticipantList] = None self._recordings: Optional[RecordingList] = None - def fetch(self) -> ConferenceInstance: + def _fetch(self) -> tuple: """ - Fetch the ConferenceInstance + Internal helper for fetch operation - - :returns: The fetched ConferenceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = self._fetch() return ConferenceInstance( self._version, payload, @@ -243,22 +315,46 @@ def fetch(self) -> ConferenceInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ConferenceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConferenceInstance + Fetch the ConferenceInstance and return response metadata - :returns: The fetched ConferenceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = await self._fetch_async() return ConferenceInstance( self._version, payload, @@ -266,20 +362,33 @@ async def fetch_async(self) -> ConferenceInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, announce_url: Union[str, object] = values.unset, announce_method: Union[str, object] = values.unset, - ) -> ConferenceInstance: + ) -> tuple: """ - Update the ConferenceInstance + Internal helper for update operation - :param status: - :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. - :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - - :returns: The updated ConferenceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +404,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + payload, _, _ = self._update( + status=status, announce_url=announce_url, announce_method=announce_method + ) return ConferenceInstance( self._version, payload, @@ -306,20 +433,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, announce_url: Union[str, object] = values.unset, announce_method: Union[str, object] = values.unset, - ) -> ConferenceInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConferenceInstance + Update the ConferenceInstance and return response metadata :param status: :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` - :returns: The updated ConferenceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, announce_url=announce_url, announce_method=announce_method + ) + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -335,10 +485,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + payload, _, _ = await self._update_async( + status=status, announce_url=announce_url, announce_method=announce_method + ) return ConferenceInstance( self._version, payload, @@ -346,6 +514,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConferenceInstance and return response metadata + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, announce_url=announce_url, announce_method=announce_method + ) + instance = ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def participants(self) -> ParticipantList: """ @@ -390,6 +584,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: :param payload: Payload response from the API """ + return ConferenceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -523,6 +718,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created: Union[date, object] = values.unset, @@ -558,6 +853,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -608,6 +904,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -624,6 +921,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceInstance and returns headers from first page + + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created: Union[date, object] = values.unset, @@ -679,7 +1074,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConferencePage(self._version, response, self._solution) + return ConferencePage(self._version, response, solution=self._solution) async def page_async( self, @@ -736,7 +1131,125 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConferencePage(self._version, response, self._solution) + return ConferencePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferencePage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferencePage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConferencePage: """ @@ -748,7 +1261,7 @@ def get_page(self, target_url: str) -> ConferencePage: :returns: Page of ConferenceInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConferencePage(self._version, response, self._solution) + return ConferencePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ConferencePage: """ @@ -760,7 +1273,7 @@ async def get_page_async(self, target_url: str) -> ConferencePage: :returns: Page of ConferenceInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConferencePage(self._version, response, self._solution) + return ConferencePage(self._version, response, solution=self._solution) def get(self, sid: str) -> ConferenceContext: """ diff --git a/twilio/rest/api/v2010/account/conference/participant.py b/twilio/rest/api/v2010/account/conference/participant.py index a93f9f9adc..1839657705 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "conference_sid": conference_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[ParticipantContext] = None @property @@ -126,6 +128,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -144,6 +164,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, muted: Union[bool, object] = values.unset, @@ -168,7 +206,7 @@ def update( :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. @@ -216,7 +254,7 @@ async def update_async( :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. @@ -240,6 +278,102 @@ async def update_async( call_sid_to_coach=call_sid_to_coach, ) + def update_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + async def update_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -275,6 +409,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ParticipantInstance @@ -282,10 +430,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -294,27 +464,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ParticipantInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ParticipantInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -323,22 +509,47 @@ def fetch(self) -> ParticipantInstance: call_sid=self._solution["call_sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -347,7 +558,24 @@ async def fetch_async(self) -> ParticipantInstance: call_sid=self._solution["call_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, muted: Union[bool, object] = values.unset, hold: Union[bool, object] = values.unset, @@ -361,24 +589,12 @@ def update( end_conference_on_exit: Union[bool, object] = values.unset, coaching: Union[bool, object] = values.unset, call_sid_to_coach: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Update the ParticipantInstance + Internal helper for update operation - :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. - :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. - :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. - :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. - :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. - :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). - :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. - :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. - :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. - :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. - :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. - - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -405,19 +621,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - conference_sid=self._solution["conference_sid"], - call_sid=self._solution["call_sid"], - ) - - async def update_async( + def update( self, muted: Union[bool, object] = values.unset, hold: Union[bool, object] = values.unset, @@ -433,7 +641,7 @@ async def update_async( call_sid_to_coach: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronous coroutine to update the ParticipantInstance + Update the ParticipantInstance :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. @@ -441,7 +649,7 @@ async def update_async( :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. @@ -450,35 +658,20 @@ async def update_async( :returns: The updated ParticipantInstance """ - - data = values.of( - { - "Muted": serialize.boolean_to_string(muted), - "Hold": serialize.boolean_to_string(hold), - "HoldUrl": hold_url, - "HoldMethod": hold_method, - "AnnounceUrl": announce_url, - "AnnounceMethod": announce_method, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "BeepOnExit": serialize.boolean_to_string(beep_on_exit), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "Coaching": serialize.boolean_to_string(coaching), - "CallSidToCoach": call_sid_to_coach, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, ) - return ParticipantInstance( self._version, payload, @@ -487,11 +680,228 @@ async def update_async( call_sid=self._solution["call_sid"], ) - def __repr__(self) -> str: + def update_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Provide a friendly representation + Update the ParticipantInstance and return response metadata - :returns: Machine friendly representation + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -505,6 +915,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -543,7 +954,7 @@ def __init__(self, version: Version, account_sid: str, conference_sid: str): **self._solution ) - def create( + def _create( self, from_: str, to: str, @@ -585,6 +996,7 @@ def create( caller_id: Union[str, object] = values.unset, call_reason: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, machine_detection: Union[str, object] = values.unset, machine_detection_timeout: Union[int, object] = values.unset, @@ -595,60 +1007,23 @@ def create( amd_status_callback_method: Union[str, object] = values.unset, trim: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, - ) -> ParticipantInstance: + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ParticipantInstance - - :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. - :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. - :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. - :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. - :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. - :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. - :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. - :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. - :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. - :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. - :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). - :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. - :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. - :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. - :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. - :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. - :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. - :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. - :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. - :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. - :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param sip_auth_username: The SIP username used for authentication. - :param sip_auth_password: The SIP password for authentication. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. - :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. - :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. - :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` - :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. - :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. - :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. - :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) - :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. - :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) - :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. - :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. - :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). - :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. - :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. - :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. - :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. - :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. - :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. - :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. - :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + Internal helper for create operation - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -703,6 +1078,7 @@ def create( "CallerId": caller_id, "CallReason": call_reason, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, "TimeLimit": time_limit, "MachineDetection": machine_detection, "MachineDetectionTimeout": machine_detection_timeout, @@ -713,6 +1089,17 @@ def create( "AmdStatusCallbackMethod": amd_status_callback_method, "Trim": trim, "CallToken": call_token, + "Passports": passports, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, + "EmergencyCallerPosition": emergency_caller_position, + "EmergencyCallerLocation": emergency_caller_location, + "EmergencyName": emergency_name, + "EmergencyAddress": emergency_address, + "EmergencyZipCode": emergency_zip_code, + "EmergencyCity": emergency_city, + "EmergencyState": emergency_state, + "EmergencyCountry": emergency_country, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -721,18 +1108,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - conference_sid=self._solution["conference_sid"], - ) - - async def create_async( + def create( self, from_: str, to: str, @@ -774,6 +1154,7 @@ async def create_async( caller_id: Union[str, object] = values.unset, call_reason: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, machine_detection: Union[str, object] = values.unset, machine_detection_timeout: Union[int, object] = values.unset, @@ -784,12 +1165,23 @@ async def create_async( amd_status_callback_method: Union[str, object] = values.unset, trim: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. - :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. @@ -800,7 +1192,7 @@ async def create_async( :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. - :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. @@ -814,7 +1206,7 @@ async def create_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. @@ -826,6 +1218,7 @@ async def create_async( :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. @@ -836,20 +1229,372 @@ async def create_async( :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + :param emergency_caller_position: The emergency caller's GPS coordinates in decimal degrees format. Format: \\\"latitude longitude\\\" (space-separated) - Latitude: decimal degrees, range -90.0 to +90.0 (negative for South, positive for North) - Longitude: decimal degrees, range -180.0 to +180.0 (negative for West, positive for East) - Precision: up to 6 decimal places recommended for meter-level accuracy Note: If the value exceeds 150 characters, only the first 150 characters will be used. + :param emergency_caller_location: The emergency caller's physical location description within a building or facility. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_name: The emergency caller's organization or entity name. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_address: The emergency caller's street address including street number and street name. Note: If the value exceeds 60 characters, only the first 60 characters will be used. + :param emergency_zip_code: The emergency caller's postal code or ZIP code. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_city: The emergency caller's city or municipality name. Should be the official city name as recognized by local authorities. Used in combination with state and country for emergency call routing. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_state: The emergency caller's state or province. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_country: The emergency caller's country. Currently supported US and CA only. Note: If the value exceeds 20 characters, only the first 20 characters will be used. :returns: The created ParticipantInstance """ - - data = values.of( - { - "From": from_, - "To": to, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "Label": label, + payload, _, _ = self._create( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + passports=passports, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + emergency_caller_position=emergency_caller_position, + emergency_caller_location=emergency_caller_location, + emergency_name=emergency_name, + emergency_address=emergency_address, + emergency_zip_code=emergency_zip_code, + emergency_city=emergency_city, + emergency_state=emergency_state, + emergency_country=emergency_country, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def create_with_http_info( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + :param emergency_caller_position: The emergency caller's GPS coordinates in decimal degrees format. Format: \\\"latitude longitude\\\" (space-separated) - Latitude: decimal degrees, range -90.0 to +90.0 (negative for South, positive for North) - Longitude: decimal degrees, range -180.0 to +180.0 (negative for West, positive for East) - Precision: up to 6 decimal places recommended for meter-level accuracy Note: If the value exceeds 150 characters, only the first 150 characters will be used. + :param emergency_caller_location: The emergency caller's physical location description within a building or facility. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_name: The emergency caller's organization or entity name. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_address: The emergency caller's street address including street number and street name. Note: If the value exceeds 60 characters, only the first 60 characters will be used. + :param emergency_zip_code: The emergency caller's postal code or ZIP code. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_city: The emergency caller's city or municipality name. Should be the official city name as recognized by local authorities. Used in combination with state and country for emergency call routing. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_state: The emergency caller's state or province. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_country: The emergency caller's country. Currently supported US and CA only. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + passports=passports, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + emergency_caller_position=emergency_caller_position, + emergency_caller_location=emergency_caller_location, + emergency_name=emergency_name, + emergency_address=emergency_address, + emergency_zip_code=emergency_zip_code, + emergency_city=emergency_city, + emergency_state=emergency_state, + emergency_country=emergency_country, + ) + instance = ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, "Timeout": timeout, "Record": serialize.boolean_to_string(record), "Muted": serialize.boolean_to_string(muted), @@ -892,6 +1637,7 @@ async def create_async( "CallerId": caller_id, "CallReason": call_reason, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, "TimeLimit": time_limit, "MachineDetection": machine_detection, "MachineDetectionTimeout": machine_detection_timeout, @@ -902,6 +1648,17 @@ async def create_async( "AmdStatusCallbackMethod": amd_status_callback_method, "Trim": trim, "CallToken": call_token, + "Passports": passports, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, + "EmergencyCallerPosition": emergency_caller_position, + "EmergencyCallerLocation": emergency_caller_location, + "EmergencyName": emergency_name, + "EmergencyAddress": emergency_address, + "EmergencyZipCode": emergency_zip_code, + "EmergencyCity": emergency_city, + "EmergencyState": emergency_state, + "EmergencyCountry": emergency_country, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -910,16 +1667,410 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + :param emergency_caller_position: The emergency caller's GPS coordinates in decimal degrees format. Format: \\\"latitude longitude\\\" (space-separated) - Latitude: decimal degrees, range -90.0 to +90.0 (negative for South, positive for North) - Longitude: decimal degrees, range -180.0 to +180.0 (negative for West, positive for East) - Precision: up to 6 decimal places recommended for meter-level accuracy Note: If the value exceeds 150 characters, only the first 150 characters will be used. + :param emergency_caller_location: The emergency caller's physical location description within a building or facility. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_name: The emergency caller's organization or entity name. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_address: The emergency caller's street address including street number and street name. Note: If the value exceeds 60 characters, only the first 60 characters will be used. + :param emergency_zip_code: The emergency caller's postal code or ZIP code. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_city: The emergency caller's city or municipality name. Should be the official city name as recognized by local authorities. Used in combination with state and country for emergency call routing. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_state: The emergency caller's state or province. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_country: The emergency caller's country. Currently supported US and CA only. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + passports=passports, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + emergency_caller_position=emergency_caller_position, + emergency_caller_location=emergency_caller_location, + emergency_name=emergency_name, + emergency_address=emergency_address, + emergency_zip_code=emergency_zip_code, + emergency_city=emergency_city, + emergency_state=emergency_state, + emergency_country=emergency_country, + ) + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + async def create_with_http_info_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + passports: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + emergency_caller_position: Union[str, object] = values.unset, + emergency_caller_location: Union[str, object] = values.unset, + emergency_name: Union[str, object] = values.unset, + emergency_address: Union[str, object] = values.unset, + emergency_zip_code: Union[str, object] = values.unset, + emergency_city: Union[str, object] = values.unset, + emergency_state: Union[str, object] = values.unset, + emergency_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param passports: The STIR/SHAKEN passport for this call, provided as a base64 encoded string. Multiple passports (at max 5) are comma separated and provided as base64 encoded string + :param client_notification_url: The URL that we should use to deliver `push call notification`. + :param caller_display_name: The name that populates the display name in the From header. Must be between 2 and 255 characters. Only applicable for calls to sip address. + :param emergency_caller_position: The emergency caller's GPS coordinates in decimal degrees format. Format: \\\"latitude longitude\\\" (space-separated) - Latitude: decimal degrees, range -90.0 to +90.0 (negative for South, positive for North) - Longitude: decimal degrees, range -180.0 to +180.0 (negative for West, positive for East) - Precision: up to 6 decimal places recommended for meter-level accuracy Note: If the value exceeds 150 characters, only the first 150 characters will be used. + :param emergency_caller_location: The emergency caller's physical location description within a building or facility. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_name: The emergency caller's organization or entity name. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_address: The emergency caller's street address including street number and street name. Note: If the value exceeds 60 characters, only the first 60 characters will be used. + :param emergency_zip_code: The emergency caller's postal code or ZIP code. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_city: The emergency caller's city or municipality name. Should be the official city name as recognized by local authorities. Used in combination with state and country for emergency call routing. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_state: The emergency caller's state or province. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + :param emergency_country: The emergency caller's country. Currently supported US and CA only. Note: If the value exceeds 20 characters, only the first 20 characters will be used. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + from_=from_, + to=to, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + label=label, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_record=conference_record, + conference_trim=conference_trim, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + region=region, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + conference_recording_status_callback_event=conference_recording_status_callback_event, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + jitter_buffer_size=jitter_buffer_size, + byoc=byoc, + caller_id=caller_id, + call_reason=call_reason, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + time_limit=time_limit, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + amd_status_callback=amd_status_callback, + amd_status_callback_method=amd_status_callback_method, + trim=trim, + call_token=call_token, + passports=passports, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + emergency_caller_position=emergency_caller_position, + emergency_caller_location=emergency_caller_location, + emergency_name=emergency_name, + emergency_address=emergency_address, + emergency_zip_code=emergency_zip_code, + emergency_city=emergency_city, + emergency_state=emergency_state, + emergency_country=emergency_country, ) - - return ParticipantInstance( + instance = ParticipantInstance( self._version, payload, account_sid=self._solution["account_sid"], conference_sid=self._solution["conference_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -987,6 +2138,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, muted: Union[bool, object] = values.unset, @@ -1012,6 +2227,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( muted=muted, @@ -1047,6 +2263,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1058,6 +2275,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, muted: Union[bool, object] = values.unset, @@ -1098,7 +2383,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1140,7 +2425,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -1152,7 +2525,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -1164,7 +2537,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, call_sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/api/v2010/account/conference/recording.py b/twilio/rest/api/v2010/account/conference/recording.py index 12008ed37f..cca644f741 100644 --- a/twilio/rest/api/v2010/account/conference/recording.py +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -102,6 +103,7 @@ def __init__( "conference_sid": conference_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -139,6 +141,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -157,6 +177,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "RecordingInstance.Status", @@ -193,6 +231,42 @@ async def update_async( pause_behavior=pause_behavior, ) + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + pause_behavior=pause_behavior, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -228,6 +302,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -235,10 +323,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -247,27 +357,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RecordingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RecordingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() return RecordingInstance( self._version, payload, @@ -276,22 +402,47 @@ def fetch(self) -> RecordingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RecordingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() return RecordingInstance( self._version, payload, @@ -300,18 +451,33 @@ async def fetch_async(self) -> RecordingInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: "RecordingInstance.Status", pause_behavior: Union[str, object] = values.unset, - ) -> RecordingInstance: + ) -> tuple: """ - Update the RecordingInstance - - :param status: - :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + Internal helper for update operation - :returns: The updated RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,10 +492,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + payload, _, _ = self._update(status=status, pause_behavior=pause_behavior) return RecordingInstance( self._version, payload, @@ -338,18 +518,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "RecordingInstance.Status", pause_behavior: Union[str, object] = values.unset, - ) -> RecordingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the RecordingInstance + Update the RecordingInstance and return response metadata :param status: :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. - :returns: The updated RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -364,10 +567,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + payload, _, _ = await self._update_async( + status=status, pause_behavior=pause_behavior + ) return RecordingInstance( self._version, payload, @@ -376,6 +595,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -394,6 +638,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -504,6 +749,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created: Union[date, object] = values.unset, @@ -529,6 +844,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -564,6 +880,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -575,6 +892,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created: Union[date, object] = values.unset, @@ -615,7 +1000,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -657,7 +1042,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RecordingPage: """ @@ -669,7 +1142,7 @@ def get_page(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RecordingPage: """ @@ -681,7 +1154,7 @@ async def get_page_async(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RecordingContext: """ diff --git a/twilio/rest/api/v2010/account/connect_app.py b/twilio/rest/api/v2010/account/connect_app.py index 689a2b184a..6f6f0513c1 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ConnectAppContext] = None @property @@ -110,6 +112,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectAppInstance": """ Fetch the ConnectAppInstance @@ -128,6 +148,24 @@ async def fetch_async(self) -> "ConnectAppInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, authorize_redirect_url: Union[str, object] = values.unset, @@ -204,6 +242,82 @@ async def update_async( permissions=permissions, ) + def update_with_http_info( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConnectAppInstance with HTTP info + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + async def update_with_http_info_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectAppInstance with HTTP info + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +349,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectAppInstance @@ -242,10 +370,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectAppInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -254,27 +404,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectAppInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ConnectAppInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ConnectAppInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ConnectAppInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectAppInstance: + """ + Fetch the ConnectAppInstance + + :returns: The fetched ConnectAppInstance + """ + payload, _, _ = self._fetch() return ConnectAppInstance( self._version, payload, @@ -282,22 +448,46 @@ def fetch(self) -> ConnectAppInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ConnectAppInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConnectAppInstance + Fetch the ConnectAppInstance and return response metadata - :returns: The fetched ConnectAppInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConnectAppInstance: + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + payload, _, _ = await self._fetch_async() return ConnectAppInstance( self._version, payload, @@ -305,7 +495,23 @@ async def fetch_async(self) -> ConnectAppInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectAppInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, authorize_redirect_url: Union[str, object] = values.unset, company_name: Union[str, object] = values.unset, @@ -317,20 +523,12 @@ def update( permissions: Union[ List["ConnectAppInstance.Permission"], object ] = values.unset, - ) -> ConnectAppInstance: + ) -> tuple: """ - Update the ConnectAppInstance - - :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. - :param company_name: The company name to set for the Connect App. - :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. - :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. - :param description: A description of the Connect App. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param homepage_url: A public URL where users can obtain more information about this Connect App. - :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + Internal helper for update operation - :returns: The updated ConnectAppInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -351,10 +549,47 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + payload, _, _ = self._update( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) return ConnectAppInstance( self._version, payload, @@ -362,7 +597,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, authorize_redirect_url: Union[str, object] = values.unset, company_name: Union[str, object] = values.unset, @@ -374,9 +609,9 @@ async def update_async( permissions: Union[ List["ConnectAppInstance.Permission"], object ] = values.unset, - ) -> ConnectAppInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConnectAppInstance + Update the ConnectAppInstance and return response metadata :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. :param company_name: The company name to set for the Connect App. @@ -387,7 +622,44 @@ async def update_async( :param homepage_url: A public URL where users can obtain more information about this Connect App. :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. - :returns: The updated ConnectAppInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,10 +680,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + payload, _, _ = await self._update_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) return ConnectAppInstance( self._version, payload, @@ -419,6 +728,51 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectAppInstance and return response metadata + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + instance = ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -437,6 +791,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: :param payload: Payload response from the API """ + return ConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -518,6 +873,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -537,6 +942,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,6 +969,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -571,6 +978,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConnectAppInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -602,7 +1059,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConnectAppPage(self._version, response, self._solution) + return ConnectAppPage(self._version, response, solution=self._solution) async def page_async( self, @@ -635,7 +1092,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConnectAppPage(self._version, response, self._solution) + return ConnectAppPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectAppPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectAppPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConnectAppPage: """ @@ -647,7 +1174,7 @@ def get_page(self, target_url: str) -> ConnectAppPage: :returns: Page of ConnectAppInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConnectAppPage(self._version, response, self._solution) + return ConnectAppPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ConnectAppPage: """ @@ -659,7 +1186,7 @@ async def get_page_async(self, target_url: str) -> ConnectAppPage: :returns: Page of ConnectAppInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConnectAppPage(self._version, response, self._solution) + return ConnectAppPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ConnectAppContext: """ diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py index c7c1eebcfd..948519d653 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ class VoiceReceiveMode(object): :ivar emergency_address_status: :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. :ivar status: + :ivar type: The phone number type. """ def __init__( @@ -148,11 +150,13 @@ def __init__( ] = payload.get("emergency_address_status") self.bundle_sid: Optional[str] = payload.get("bundle_sid") self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") self._solution = { "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[IncomingPhoneNumberContext] = None @property @@ -189,6 +193,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IncomingPhoneNumberInstance": """ Fetch the IncomingPhoneNumberInstance @@ -207,6 +229,24 @@ async def fetch_async(self) -> "IncomingPhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, account_sid: Union[str, object] = values.unset, @@ -377,6 +417,176 @@ async def update_async( bundle_sid=bundle_sid, ) + def update_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the IncomingPhoneNumberInstance with HTTP info + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + async def update_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance with HTTP info + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + @property def assigned_add_ons(self) -> AssignedAddOnList: """ @@ -417,6 +627,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._assigned_add_ons: Optional[AssignedAddOnList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IncomingPhoneNumberInstance @@ -424,10 +648,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IncomingPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -436,27 +682,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IncomingPhoneNumberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IncomingPhoneNumberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IncomingPhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IncomingPhoneNumberInstance: + """ + Fetch the IncomingPhoneNumberInstance + + :returns: The fetched IncomingPhoneNumberInstance + """ + payload, _, _ = self._fetch() return IncomingPhoneNumberInstance( self._version, payload, @@ -464,22 +726,46 @@ def fetch(self) -> IncomingPhoneNumberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> IncomingPhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + Fetch the IncomingPhoneNumberInstance and return response metadata - :returns: The fetched IncomingPhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return IncomingPhoneNumberInstance( self._version, payload, @@ -487,7 +773,23 @@ async def fetch_async(self) -> IncomingPhoneNumberInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, account_sid: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -516,35 +818,12 @@ def update( identity_sid: Union[str, object] = values.unset, address_sid: Union[str, object] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> IncomingPhoneNumberInstance: + ) -> tuple: """ - Update the IncomingPhoneNumberInstance + Internal helper for update operation - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). - :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. - :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The updated IncomingPhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -582,18 +861,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, account_sid: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -624,7 +896,7 @@ async def update_async( bundle_sid: Union[str, object] = values.unset, ) -> IncomingPhoneNumberInstance: """ - Asynchronous coroutine to update the IncomingPhoneNumberInstance + Update the IncomingPhoneNumberInstance :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. @@ -652,46 +924,31 @@ async def update_async( :returns: The updated IncomingPhoneNumberInstance """ - - data = values.of( - { - "AccountSid": account_sid, - "ApiVersion": api_version, - "FriendlyName": friendly_name, - "SmsApplicationSid": sms_application_sid, - "SmsFallbackMethod": sms_fallback_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsMethod": sms_method, - "SmsUrl": sms_url, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "VoiceApplicationSid": voice_application_sid, - "VoiceCallerIdLookup": serialize.boolean_to_string( - voice_caller_id_lookup - ), - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - "EmergencyStatus": emergency_status, - "EmergencyAddressSid": emergency_address_sid, - "TrunkSid": trunk_sid, - "VoiceReceiveMode": voice_receive_mode, - "IdentitySid": identity_sid, - "AddressSid": address_sid, - "BundleSid": bundle_sid, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, ) - return IncomingPhoneNumberInstance( self._version, payload, @@ -699,76 +956,9 @@ async def update_async( sid=self._solution["sid"], ) - @property - def assigned_add_ons(self) -> AssignedAddOnList: - """ - Access the assigned_add_ons - """ - if self._assigned_add_ons is None: - self._assigned_add_ons = AssignedAddOnList( - self._version, - self._solution["account_sid"], - self._solution["sid"], - ) - return self._assigned_add_ons - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class IncomingPhoneNumberPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: - """ - Build an instance of IncomingPhoneNumberInstance - - :param payload: Payload response from the API - """ - return IncomingPhoneNumberInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class IncomingPhoneNumberList(ListResource): - - def __init__(self, version: Version, account_sid: str): - """ - Initialize the IncomingPhoneNumberList - - :param version: Version that contains the resource - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( - **self._solution - ) - - self._local: Optional[LocalList] = None - self._mobile: Optional[MobileList] = None - self._toll_free: Optional[TollFreeList] = None - - def create( + def update_with_http_info( self, + account_sid: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, sms_application_sid: Union[str, object] = values.unset, @@ -789,44 +979,439 @@ def create( ] = values.unset, emergency_address_sid: Union[str, object] = values.unset, trunk_sid: Union[str, object] = values.unset, - identity_sid: Union[str, object] = values.unset, - address_sid: Union[str, object] = values.unset, voice_receive_mode: Union[ "IncomingPhoneNumberInstance.VoiceReceiveMode", object ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, bundle_sid: Union[str, object] = values.unset, - phone_number: Union[str, object] = values.unset, - area_code: Union[str, object] = values.unset, - ) -> IncomingPhoneNumberInstance: + ) -> ApiResponse: """ - Create the IncomingPhoneNumberInstance + Update the IncomingPhoneNumberInstance and return response metadata - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). - :returns: The created IncomingPhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + payload, _, _ = await self._update_async( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance and return response metadata + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + instance = IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: + """ + Access the assigned_add_ons + """ + if self._assigned_add_ons is None: + self._assigned_add_ons = AssignedAddOnList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class IncomingPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + """ + Build an instance of IncomingPhoneNumberInstance + + :param payload: Payload response from the API + """ + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class IncomingPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IncomingPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( + **self._solution + ) + + self._local: Optional[LocalList] = None + self._mobile: Optional[MobileList] = None + self._toll_free: Optional[TollFreeList] = None + + def _create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -863,17 +1448,104 @@ def create( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + :returns: The created IncomingPhoneNumberInstance + """ + payload, _, _ = self._create( + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, ) - return IncomingPhoneNumberInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, api_version: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -903,9 +1575,9 @@ async def create_async( bundle_sid: Union[str, object] = values.unset, phone_number: Union[str, object] = values.unset, area_code: Union[str, object] = values.unset, - ) -> IncomingPhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronously create the IncomingPhoneNumberInstance + Create the IncomingPhoneNumberInstance and return response metadata :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. @@ -932,7 +1604,75 @@ async def create_async( :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). - :returns: The created IncomingPhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + instance = IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -969,15 +1709,194 @@ async def create_async( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronously create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + payload, _, _ = await self._create_async( + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IncomingPhoneNumberInstance and return response metadata + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, ) - - return IncomingPhoneNumberInstance( + instance = IncomingPhoneNumberInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -1057,6 +1976,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IncomingPhoneNumberInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IncomingPhoneNumberInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, beta: Union[bool, object] = values.unset, @@ -1084,6 +2079,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -1122,6 +2118,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1134,6 +2131,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IncomingPhoneNumberInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IncomingPhoneNumberInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, beta: Union[bool, object] = values.unset, @@ -1177,7 +2248,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return IncomingPhoneNumberPage(self._version, response, self._solution) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1222,7 +2293,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return IncomingPhoneNumberPage(self._version, response, self._solution) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IncomingPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IncomingPhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IncomingPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IncomingPhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IncomingPhoneNumberPage: """ @@ -1234,7 +2399,7 @@ def get_page(self, target_url: str) -> IncomingPhoneNumberPage: :returns: Page of IncomingPhoneNumberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return IncomingPhoneNumberPage(self._version, response, self._solution) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: """ @@ -1246,7 +2411,7 @@ async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: :returns: Page of IncomingPhoneNumberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return IncomingPhoneNumberPage(self._version, response, self._solution) + return IncomingPhoneNumberPage(self._version, response, solution=self._solution) @property def local(self) -> LocalList: diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py index 52fe2a52af..83acaedda3 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "resource_sid": resource_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnContext] = None @property @@ -110,6 +112,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AssignedAddOnInstance": """ Fetch the AssignedAddOnInstance @@ -128,6 +148,24 @@ async def fetch_async(self) -> "AssignedAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AssignedAddOnExtensionList: """ @@ -170,6 +208,20 @@ def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: s self._extensions: Optional[AssignedAddOnExtensionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AssignedAddOnInstance @@ -177,10 +229,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssignedAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -189,27 +263,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AssignedAddOnInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AssignedAddOnInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AssignedAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnInstance: + """ + Fetch the AssignedAddOnInstance + + :returns: The fetched AssignedAddOnInstance + """ + payload, _, _ = self._fetch() return AssignedAddOnInstance( self._version, payload, @@ -218,22 +308,47 @@ def fetch(self) -> AssignedAddOnInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AssignedAddOnInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AssignedAddOnInstance + Fetch the AssignedAddOnInstance and return response metadata - :returns: The fetched AssignedAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AssignedAddOnInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + payload, _, _ = await self._fetch_async() return AssignedAddOnInstance( self._version, payload, @@ -242,6 +357,23 @@ async def fetch_async(self) -> AssignedAddOnInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def extensions(self) -> AssignedAddOnExtensionList: """ @@ -274,6 +406,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: :param payload: Payload response from the API """ + return AssignedAddOnInstance( self._version, payload, @@ -312,13 +445,12 @@ def __init__(self, version: Version, account_sid: str, resource_sid: str): **self._solution ) - def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + def _create(self, installed_add_on_sid: str) -> tuple: """ - Create the AssignedAddOnInstance - - :param installed_add_on_sid: The SID that identifies the Add-on installation. + Internal helper for create operation - :returns: The created AssignedAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -332,10 +464,19 @@ def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + payload, _, _ = self._create(installed_add_on_sid=installed_add_on_sid) return AssignedAddOnInstance( self._version, payload, @@ -343,13 +484,31 @@ def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: resource_sid=self._solution["resource_sid"], ) - async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + def create_with_http_info(self, installed_add_on_sid: str) -> ApiResponse: """ - Asynchronously create the AssignedAddOnInstance + Create the AssignedAddOnInstance and return response metadata :param installed_add_on_sid: The SID that identifies the Add-on installation. - :returns: The created AssignedAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + installed_add_on_sid=installed_add_on_sid + ) + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, installed_add_on_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,10 +522,21 @@ async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Asynchronously create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + payload, _, _ = await self._create_async( + installed_add_on_sid=installed_add_on_sid + ) return AssignedAddOnInstance( self._version, payload, @@ -374,6 +544,27 @@ async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance resource_sid=self._solution["resource_sid"], ) + async def create_with_http_info_async( + self, installed_add_on_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AssignedAddOnInstance and return response metadata + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + installed_add_on_sid=installed_add_on_sid + ) + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -424,6 +615,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -443,6 +684,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -469,6 +711,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -477,6 +720,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssignedAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -508,7 +801,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AssignedAddOnPage(self._version, response, self._solution) + return AssignedAddOnPage(self._version, response, solution=self._solution) async def page_async( self, @@ -541,7 +834,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AssignedAddOnPage(self._version, response, self._solution) + return AssignedAddOnPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssignedAddOnPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssignedAddOnPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AssignedAddOnPage: """ @@ -553,7 +916,7 @@ def get_page(self, target_url: str) -> AssignedAddOnPage: :returns: Page of AssignedAddOnInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AssignedAddOnPage(self._version, response, self._solution) + return AssignedAddOnPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AssignedAddOnPage: """ @@ -565,7 +928,7 @@ async def get_page_async(self, target_url: str) -> AssignedAddOnPage: :returns: Page of AssignedAddOnInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AssignedAddOnPage(self._version, response, self._solution) + return AssignedAddOnPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AssignedAddOnContext: """ diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py index 1a7d9cdc34..f9d3e5d83d 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "assigned_add_on_sid": assigned_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnExtensionContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "AssignedAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,20 +161,30 @@ def __init__( **self._solution ) - def fetch(self) -> AssignedAddOnExtensionInstance: + def _fetch(self) -> tuple: """ - Fetch the AssignedAddOnExtensionInstance - + Internal helper for fetch operation - :returns: The fetched AssignedAddOnExtensionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnExtensionInstance: + """ + Fetch the AssignedAddOnExtensionInstance + + :returns: The fetched AssignedAddOnExtensionInstance + """ + payload, _, _ = self._fetch() return AssignedAddOnExtensionInstance( self._version, payload, @@ -164,22 +194,48 @@ def fetch(self) -> AssignedAddOnExtensionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AssignedAddOnExtensionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + Fetch the AssignedAddOnExtensionInstance and return response metadata - :returns: The fetched AssignedAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AssignedAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() return AssignedAddOnExtensionInstance( self._version, payload, @@ -189,6 +245,24 @@ async def fetch_async(self) -> AssignedAddOnExtensionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +281,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstanc :param payload: Payload response from the API """ + return AssignedAddOnExtensionInstance( self._version, payload, @@ -304,6 +379,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -323,6 +448,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -349,6 +475,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -357,6 +484,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssignedAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -388,7 +565,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -421,7 +600,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: """ @@ -433,7 +688,9 @@ def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: :returns: Page of AssignedAddOnExtensionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: """ @@ -445,7 +702,9 @@ async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: :returns: Page of AssignedAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + return AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> AssignedAddOnExtensionContext: """ diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/local.py b/twilio/rest/api/v2010/account/incoming_phone_number/local.py index af67fb0a2d..06ce14ba9f 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/local.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -219,35 +221,12 @@ def create( "LocalInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> LocalInstance: + ) -> tuple: """ - Create the LocalInstance - - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + Internal helper for create operation - :returns: The created LocalInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -285,15 +264,97 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -320,9 +381,9 @@ async def create_async( "LocalInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> LocalInstance: + ) -> ApiResponse: """ - Asynchronously create the LocalInstance + Create the LocalInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -348,7 +409,71 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created LocalInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -386,14 +511,183 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Asynchronously create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the LocalInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -472,6 +766,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LocalInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LocalInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, beta: Union[bool, object] = values.unset, @@ -499,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -537,6 +908,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -549,6 +921,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LocalInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LocalInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, beta: Union[bool, object] = values.unset, @@ -592,7 +1038,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -637,7 +1083,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LocalPage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LocalPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> LocalPage: """ @@ -649,7 +1189,7 @@ def get_page(self, target_url: str) -> LocalPage: :returns: Page of LocalInstance """ response = self._version.domain.twilio.request("GET", target_url) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> LocalPage: """ @@ -661,7 +1201,7 @@ async def get_page_async(self, target_url: str) -> LocalPage: :returns: Page of LocalInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return LocalPage(self._version, response, self._solution) + return LocalPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py index 27fc8a0e9f..2087c91ae3 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -221,35 +223,12 @@ def create( "MobileInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> MobileInstance: + ) -> tuple: """ - Create the MobileInstance + Internal helper for create operation - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The created MobileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -287,15 +266,99 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -324,9 +387,9 @@ async def create_async( "MobileInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> MobileInstance: + ) -> ApiResponse: """ - Asynchronously create the MobileInstance + Create the MobileInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -352,7 +415,73 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created MobileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -390,14 +519,187 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Asynchronously create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MobileInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -476,6 +778,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MobileInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MobileInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, beta: Union[bool, object] = values.unset, @@ -503,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -541,6 +920,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -553,6 +933,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MobileInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MobileInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, beta: Union[bool, object] = values.unset, @@ -596,7 +1050,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) async def page_async( self, @@ -641,7 +1095,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MobilePage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MobilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MobilePage: """ @@ -653,7 +1201,7 @@ def get_page(self, target_url: str) -> MobilePage: :returns: Page of MobileInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MobilePage: """ @@ -665,7 +1213,7 @@ async def get_page_async(self, target_url: str) -> MobilePage: :returns: Page of MobileInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MobilePage(self._version, response, self._solution) + return MobilePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py index 86290ff9b2..c4597aa459 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -221,35 +223,12 @@ def create( "TollFreeInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> TollFreeInstance: + ) -> tuple: """ - Create the TollFreeInstance + Internal helper for create operation - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The created TollFreeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -287,15 +266,99 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -324,9 +387,9 @@ async def create_async( "TollFreeInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> TollFreeInstance: + ) -> ApiResponse: """ - Asynchronously create the TollFreeInstance + Create the TollFreeInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -352,7 +415,73 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created TollFreeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -390,14 +519,187 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Asynchronously create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TollFreeInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -476,6 +778,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollFreeInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollFreeInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, beta: Union[bool, object] = values.unset, @@ -503,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -541,6 +920,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -553,6 +933,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollFreeInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollFreeInstance and returns headers from first page + + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, beta: Union[bool, object] = values.unset, @@ -596,7 +1050,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) async def page_async( self, @@ -641,7 +1095,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollFreePage, status code, and headers + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollFreePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TollFreePage: """ @@ -653,7 +1201,7 @@ def get_page(self, target_url: str) -> TollFreePage: :returns: Page of TollFreeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TollFreePage: """ @@ -665,7 +1213,7 @@ async def get_page_async(self, target_url: str) -> TollFreePage: :returns: Page of TollFreeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TollFreePage(self._version, response, self._solution) + return TollFreePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/key.py b/twilio/rest/api/v2010/account/key.py index 8b18dbd4ba..2683e7ab3c 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[KeyContext] = None @property @@ -88,6 +90,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "KeyInstance": """ Fetch the KeyInstance @@ -106,6 +126,24 @@ async def fetch_async(self) -> "KeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": """ Update the KeyInstance @@ -132,6 +170,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the KeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -161,6 +227,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): } self._uri = "/Accounts/{account_sid}/Keys/{sid}.json".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the KeyInstance @@ -168,10 +248,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -180,27 +282,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KeyInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> KeyInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the KeyInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched KeyInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> KeyInstance: + """ + Fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + payload, _, _ = self._fetch() return KeyInstance( self._version, payload, @@ -208,22 +326,46 @@ def fetch(self) -> KeyInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> KeyInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the KeyInstance + Fetch the KeyInstance and return response metadata - :returns: The fetched KeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> KeyInstance: + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + payload, _, _ = await self._fetch_async() return KeyInstance( self._version, payload, @@ -231,13 +373,28 @@ async def fetch_async(self) -> KeyInstance: sid=self._solution["sid"], ) - def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the KeyInstance + Asynchronous coroutine to fetch the KeyInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated KeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -251,10 +408,19 @@ def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstanc headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstance: + """ + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return KeyInstance( self._version, payload, @@ -262,15 +428,33 @@ def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstanc sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> KeyInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the KeyInstance + Update the KeyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated KeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -284,10 +468,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> KeyInstance: + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return KeyInstance( self._version, payload, @@ -295,6 +490,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -313,6 +529,7 @@ def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: :param payload: Payload response from the API """ + return KeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -394,6 +611,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -413,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -439,6 +707,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -447,6 +716,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -478,7 +797,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return KeyPage(self._version, response, self._solution) + return KeyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -511,7 +830,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return KeyPage(self._version, response, self._solution) + return KeyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> KeyPage: """ @@ -523,7 +912,7 @@ def get_page(self, target_url: str) -> KeyPage: :returns: Page of KeyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return KeyPage(self._version, response, self._solution) + return KeyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> KeyPage: """ @@ -535,7 +924,7 @@ async def get_page_async(self, target_url: str) -> KeyPage: :returns: Page of KeyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return KeyPage(self._version, response, self._solution) + return KeyPage(self._version, response, solution=self._solution) def get(self, sid: str) -> KeyContext: """ diff --git a/twilio/rest/api/v2010/account/message/__init__.py b/twilio/rest/api/v2010/account/message/__init__.py index f41c1c5ad7..38182a2c9b 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,9 @@ class Status(object): PARTIALLY_DELIVERED = "partially_delivered" CANCELED = "canceled" + class TrafficType(object): + FREE = "free" + class UpdateStatus(object): CANCELED = "canceled" @@ -130,6 +134,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -166,6 +171,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -184,6 +207,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -220,6 +261,42 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + status=status, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + status=status, + ) + @property def feedback(self) -> FeedbackList: """ @@ -268,6 +345,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._feedback: Optional[FeedbackList] = None self._media: Optional[MediaList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -275,10 +366,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -287,27 +400,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -315,22 +444,46 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -338,18 +491,32 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, body: Union[str, object] = values.unset, status: Union["MessageInstance.UpdateStatus", object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string - :param status: + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -364,10 +531,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + payload, _, _ = self._update(body=body, status=status) return MessageInstance( self._version, payload, @@ -375,18 +556,38 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, body: Union[str, object] = values.unset, status: Union["MessageInstance.UpdateStatus", object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance and return response metadata :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string :param status: - :returns: The updated MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body, status=status) + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -401,10 +602,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async(body=body, status=status) return MessageInstance( self._version, payload, @@ -412,6 +627,30 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + body=body, status=status + ) + instance = MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def feedback(self) -> FeedbackList: """ @@ -456,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -487,7 +727,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Messages.json".format(**self._solution) - def create( + def _create( self, to: str, status_callback: Union[str, object] = values.unset, @@ -505,6 +745,7 @@ def create( ] = values.unset, smart_encoded: Union[bool, object] = values.unset, persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, shorten_urls: Union[bool, object] = values.unset, schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, send_at: Union[datetime, object] = values.unset, @@ -512,39 +753,17 @@ def create( content_variables: Union[str, object] = values.unset, risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, content_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance - - :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. - :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). - :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. - :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. - :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. - :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used - :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) - :param force_delivery: Reserved - :param content_retention: - :param address_retention: - :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. - :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). - :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. - :param schedule_type: - :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. - :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. - :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. - :param risk_check: - :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. - :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). - :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. - :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -561,6 +780,7 @@ def create( "AddressRetention": address_retention, "SmartEncoded": serialize.boolean_to_string(smart_encoded), "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, "ShortenUrls": serialize.boolean_to_string(shorten_urls), "ScheduleType": schedule_type, "SendAt": serialize.iso8601_datetime(send_at), @@ -568,6 +788,7 @@ def create( "ContentVariables": content_variables, "RiskCheck": risk_check, "From": from_, + "FallbackFrom": fallback_from, "MessagingServiceSid": messaging_service_sid, "Body": body, "MediaUrl": serialize.map(media_url, lambda e: e), @@ -580,15 +801,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MessageInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - - async def create_async( + def create( self, to: str, status_callback: Union[str, object] = values.unset, @@ -606,6 +823,7 @@ async def create_async( ] = values.unset, smart_encoded: Union[bool, object] = values.unset, persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, shorten_urls: Union[bool, object] = values.unset, schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, send_at: Union[datetime, object] = values.unset, @@ -613,13 +831,14 @@ async def create_async( content_variables: Union[str, object] = values.unset, risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, content_sid: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronously create the MessageInstance + Create the MessageInstance :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). @@ -633,6 +852,7 @@ async def create_async( :param address_retention: :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. :param schedule_type: :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. @@ -640,6 +860,7 @@ async def create_async( :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. :param risk_check: :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. @@ -647,49 +868,400 @@ async def create_async( :returns: The created MessageInstance """ - - data = values.of( - { - "To": to, - "StatusCallback": status_callback, - "ApplicationSid": application_sid, - "MaxPrice": max_price, - "ProvideFeedback": serialize.boolean_to_string(provide_feedback), - "Attempt": attempt, - "ValidityPeriod": validity_period, - "ForceDelivery": serialize.boolean_to_string(force_delivery), - "ContentRetention": content_retention, - "AddressRetention": address_retention, - "SmartEncoded": serialize.boolean_to_string(smart_encoded), - "PersistentAction": serialize.map(persistent_action, lambda e: e), - "ShortenUrls": serialize.boolean_to_string(shorten_urls), - "ScheduleType": schedule_type, - "SendAt": serialize.iso8601_datetime(send_at), - "SendAsMms": serialize.boolean_to_string(send_as_mms), - "ContentVariables": content_variables, - "RiskCheck": risk_check, - "From": from_, - "MessagingServiceSid": messaging_service_sid, - "Body": body, - "MediaUrl": serialize.map(media_url, lambda e: e), - "ContentSid": content_sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, ) - return MessageInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - def stream( + def create_with_http_info( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "FallbackFrom": fallback_from, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( self, to: Union[str, object] = values.unset, from_: Union[str, object] = values.unset, @@ -705,8 +1277,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -747,8 +1319,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -773,6 +1345,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, to: Union[str, object] = values.unset, @@ -788,8 +1442,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -802,6 +1456,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( to=to, @@ -829,8 +1484,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -843,6 +1498,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -856,6 +1512,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, to: Union[str, object] = values.unset, @@ -871,8 +1607,8 @@ def page( Retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -902,7 +1638,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -919,8 +1655,8 @@ async def page_async( Asynchronously retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -950,7 +1686,107 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -962,7 +1798,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -974,7 +1810,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/api/v2010/account/message/feedback.py b/twilio/rest/api/v2010/account/message/feedback.py index cda2de2ff6..5922ead4e2 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -95,15 +96,14 @@ def __init__(self, version: Version, account_sid: str, message_sid: str): ) ) - def create( + def _create( self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset - ) -> FeedbackInstance: + ) -> tuple: """ - Create the FeedbackInstance + Internal helper for create operation - :param outcome: - - :returns: The created FeedbackInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -117,10 +117,21 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + payload, _, _ = self._create(outcome=outcome) return FeedbackInstance( self._version, payload, @@ -128,15 +139,33 @@ def create( message_sid=self._solution["message_sid"], ) - async def create_async( + def create_with_http_info( self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset - ) -> FeedbackInstance: + ) -> ApiResponse: """ - Asynchronously create the FeedbackInstance + Create the FeedbackInstance and return response metadata :param outcome: - :returns: The created FeedbackInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(outcome=outcome) + instance = FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -150,10 +179,21 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Asynchronously create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + payload, _, _ = await self._create_async(outcome=outcome) return FeedbackInstance( self._version, payload, @@ -161,6 +201,25 @@ async def create_async( message_sid=self._solution["message_sid"], ) + async def create_with_http_info_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the FeedbackInstance and return response metadata + + :param outcome: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(outcome=outcome) + instance = FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/message/media.py b/twilio/rest/api/v2010/account/message/media.py index b5d2926d12..d15bc20f18 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[MediaContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MediaInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MediaInstance": """ Fetch the MediaInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "MediaInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,6 +188,20 @@ def __init__(self, version: Version, account_sid: str, message_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MediaInstance @@ -157,10 +209,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MediaInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -169,27 +243,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MediaInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MediaInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MediaInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MediaInstance: + """ + Fetch the MediaInstance + + :returns: The fetched MediaInstance + """ + payload, _, _ = self._fetch() return MediaInstance( self._version, payload, @@ -198,22 +288,47 @@ def fetch(self) -> MediaInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MediaInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MediaInstance + Fetch the MediaInstance and return response metadata - :returns: The fetched MediaInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + payload, _, _ = await self._fetch_async() return MediaInstance( self._version, payload, @@ -222,6 +337,23 @@ async def fetch_async(self) -> MediaInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +372,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: :param payload: Payload response from the API """ + return MediaInstance( self._version, payload, @@ -350,6 +483,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MediaInstance and returns headers from first page + + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MediaInstance and returns headers from first page + + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created: Union[datetime, object] = values.unset, @@ -375,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -410,6 +614,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -421,6 +626,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MediaInstance and returns headers from first page + + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MediaInstance and returns headers from first page + + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created: Union[datetime, object] = values.unset, @@ -461,7 +734,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MediaPage(self._version, response, self._solution) + return MediaPage(self._version, response, solution=self._solution) async def page_async( self, @@ -503,7 +776,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MediaPage(self._version, response, self._solution) + return MediaPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MediaPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MediaPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MediaPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MediaPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MediaPage: """ @@ -515,7 +876,7 @@ def get_page(self, target_url: str) -> MediaPage: :returns: Page of MediaInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MediaPage(self._version, response, self._solution) + return MediaPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MediaPage: """ @@ -527,7 +888,7 @@ async def get_page_async(self, target_url: str) -> MediaPage: :returns: Page of MediaInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MediaPage(self._version, response, self._solution) + return MediaPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MediaContext: """ diff --git a/twilio/rest/api/v2010/account/new_key.py b/twilio/rest/api/v2010/account/new_key.py index ba811ec14f..525891af56 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,15 +76,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> NewKeyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the NewKeyInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + Internal helper for create operation - :returns: The created NewKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -97,23 +95,49 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return NewKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> NewKeyInstance: + ) -> ApiResponse: """ - Asynchronously create the NewKeyInstance + Create the NewKeyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created NewKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -127,14 +151,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Asynchronously create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return NewKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/new_signing_key.py b/twilio/rest/api/v2010/account/new_signing_key.py index 95341d31cb..ebbb680958 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,15 +76,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> NewSigningKeyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the NewSigningKeyInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + Internal helper for create operation - :returns: The created NewSigningKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -97,23 +95,49 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return NewSigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> NewSigningKeyInstance: + ) -> ApiResponse: """ - Asynchronously create the NewSigningKeyInstance + Create the NewSigningKeyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created NewSigningKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -127,14 +151,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Asynchronously create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return NewSigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewSigningKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/notification.py b/twilio/rest/api/v2010/account/notification.py index cd35efeabf..9afbd26354 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -116,6 +118,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -147,20 +167,30 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) - def fetch(self) -> NotificationInstance: + def _fetch(self) -> tuple: """ - Fetch the NotificationInstance - + Internal helper for fetch operation - :returns: The fetched NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + :returns: The fetched NotificationInstance + """ + payload, _, _ = self._fetch() return NotificationInstance( self._version, payload, @@ -168,22 +198,46 @@ def fetch(self) -> NotificationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> NotificationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NotificationInstance + Fetch the NotificationInstance and return response metadata - :returns: The fetched NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = await self._fetch_async() return NotificationInstance( self._version, payload, @@ -191,6 +245,22 @@ async def fetch_async(self) -> NotificationInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -209,6 +279,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -320,6 +391,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, log: Union[int, object] = values.unset, @@ -347,6 +494,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -385,6 +533,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -397,6 +546,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NotificationInstance and returns headers from first page + + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, log: Union[int, object] = values.unset, @@ -440,7 +663,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -485,7 +708,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NotificationPage, status code, and headers + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NotificationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> NotificationPage: """ @@ -497,7 +814,7 @@ def get_page(self, target_url: str) -> NotificationPage: :returns: Page of NotificationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> NotificationPage: """ @@ -509,7 +826,7 @@ async def get_page_async(self, target_url: str) -> NotificationPage: :returns: Page of NotificationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return NotificationPage(self._version, response, self._solution) + return NotificationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> NotificationContext: """ diff --git a/twilio/rest/api/v2010/account/outgoing_caller_id.py b/twilio/rest/api/v2010/account/outgoing_caller_id.py index eeb9954c75..16f29c6f7d 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[OutgoingCallerIdContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "OutgoingCallerIdInstance": """ Fetch the OutgoingCallerIdInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "OutgoingCallerIdInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "OutgoingCallerIdInstance": @@ -140,6 +178,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the OutgoingCallerIdInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +237,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the OutgoingCallerIdInstance @@ -178,10 +258,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OutgoingCallerIdInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -190,27 +292,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> OutgoingCallerIdInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the OutgoingCallerIdInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched OutgoingCallerIdInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OutgoingCallerIdInstance: + """ + Fetch the OutgoingCallerIdInstance + + :returns: The fetched OutgoingCallerIdInstance + """ + payload, _, _ = self._fetch() return OutgoingCallerIdInstance( self._version, payload, @@ -218,22 +336,46 @@ def fetch(self) -> OutgoingCallerIdInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> OutgoingCallerIdInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the OutgoingCallerIdInstance + Fetch the OutgoingCallerIdInstance and return response metadata - :returns: The fetched OutgoingCallerIdInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + payload, _, _ = await self._fetch_async() return OutgoingCallerIdInstance( self._version, payload, @@ -241,15 +383,28 @@ async def fetch_async(self) -> OutgoingCallerIdInstance: sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> OutgoingCallerIdInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the OutgoingCallerIdInstance + Asynchronous coroutine to fetch the OutgoingCallerIdInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated OutgoingCallerIdInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -263,10 +418,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return OutgoingCallerIdInstance( self._version, payload, @@ -274,15 +440,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> OutgoingCallerIdInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the OutgoingCallerIdInstance + Update the OutgoingCallerIdInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated OutgoingCallerIdInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,10 +480,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return OutgoingCallerIdInstance( self._version, payload, @@ -307,6 +502,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -325,6 +541,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: :param payload: Payload response from the API """ + return OutgoingCallerIdInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -424,6 +641,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OutgoingCallerIdInstance and returns headers from first page + + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OutgoingCallerIdInstance and returns headers from first page + + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, phone_number: Union[str, object] = values.unset, @@ -447,6 +728,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( phone_number=phone_number, @@ -479,6 +761,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -489,6 +772,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OutgoingCallerIdInstance and returns headers from first page + + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OutgoingCallerIdInstance and returns headers from first page + + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, phone_number: Union[str, object] = values.unset, @@ -526,7 +871,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return OutgoingCallerIdPage(self._version, response, self._solution) + return OutgoingCallerIdPage(self._version, response, solution=self._solution) async def page_async( self, @@ -565,7 +910,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return OutgoingCallerIdPage(self._version, response, self._solution) + return OutgoingCallerIdPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutgoingCallerIdPage, status code, and headers + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OutgoingCallerIdPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutgoingCallerIdPage, status code, and headers + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OutgoingCallerIdPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> OutgoingCallerIdPage: """ @@ -577,7 +1004,7 @@ def get_page(self, target_url: str) -> OutgoingCallerIdPage: :returns: Page of OutgoingCallerIdInstance """ response = self._version.domain.twilio.request("GET", target_url) - return OutgoingCallerIdPage(self._version, response, self._solution) + return OutgoingCallerIdPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> OutgoingCallerIdPage: """ @@ -589,7 +1016,7 @@ async def get_page_async(self, target_url: str) -> OutgoingCallerIdPage: :returns: Page of OutgoingCallerIdInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return OutgoingCallerIdPage(self._version, response, self._solution) + return OutgoingCallerIdPage(self._version, response, solution=self._solution) def get(self, sid: str) -> OutgoingCallerIdContext: """ diff --git a/twilio/rest/api/v2010/account/queue/__init__.py b/twilio/rest/api/v2010/account/queue/__init__.py index e76fda1259..dd8ca881f9 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[QueueContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the QueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "QueueInstance": """ Fetch the QueueInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "QueueInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -157,6 +195,42 @@ async def update_async( max_size=max_size, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the QueueInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + max_size=max_size, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the QueueInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + max_size=max_size, + ) + @property def members(self) -> MemberList: """ @@ -195,6 +269,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._members: Optional[MemberList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the QueueInstance @@ -202,10 +290,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the QueueInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -214,27 +324,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> QueueInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the QueueInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched QueueInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> QueueInstance: + """ + Fetch the QueueInstance + + :returns: The fetched QueueInstance + """ + payload, _, _ = self._fetch() return QueueInstance( self._version, payload, @@ -242,22 +368,46 @@ def fetch(self) -> QueueInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> QueueInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the QueueInstance + Fetch the QueueInstance and return response metadata - :returns: The fetched QueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> QueueInstance: + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + payload, _, _ = await self._fetch_async() return QueueInstance( self._version, payload, @@ -265,18 +415,32 @@ async def fetch_async(self) -> QueueInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueueInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, max_size: Union[int, object] = values.unset, - ) -> QueueInstance: + ) -> tuple: """ - Update the QueueInstance - - :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. - :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + Internal helper for update operation - :returns: The updated QueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -291,10 +455,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name, max_size=max_size) return QueueInstance( self._version, payload, @@ -302,18 +480,40 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, max_size: Union[int, object] = values.unset, - ) -> QueueInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the QueueInstance + Update the QueueInstance and return response metadata :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. - :returns: The updated QueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -328,10 +528,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, max_size=max_size + ) return QueueInstance( self._version, payload, @@ -339,6 +555,30 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the QueueInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def members(self) -> MemberList: """ @@ -370,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: :param payload: Payload response from the API """ + return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -401,16 +642,14 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) - def create( + def _create( self, friendly_name: str, max_size: Union[int, object] = values.unset - ) -> QueueInstance: + ) -> tuple: """ - Create the QueueInstance - - :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. - :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + Internal helper for create operation - :returns: The created QueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -425,24 +664,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name, max_size=max_size) return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, max_size: Union[int, object] = values.unset - ) -> QueueInstance: + ) -> ApiResponse: """ - Asynchronously create the QueueInstance + Create the QueueInstance and return response metadata :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. - :returns: The created QueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -457,14 +725,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Asynchronously create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the QueueInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -515,6 +816,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams QueueInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams QueueInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -534,6 +885,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -560,6 +912,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -568,6 +921,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists QueueInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists QueueInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -599,7 +1002,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return QueuePage(self._version, response, self._solution) + return QueuePage(self._version, response, solution=self._solution) async def page_async( self, @@ -632,7 +1035,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return QueuePage(self._version, response, self._solution) + return QueuePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueuePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = QueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueuePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = QueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> QueuePage: """ @@ -644,7 +1117,7 @@ def get_page(self, target_url: str) -> QueuePage: :returns: Page of QueueInstance """ response = self._version.domain.twilio.request("GET", target_url) - return QueuePage(self._version, response, self._solution) + return QueuePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> QueuePage: """ @@ -656,7 +1129,7 @@ async def get_page_async(self, target_url: str) -> QueuePage: :returns: Page of QueueInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return QueuePage(self._version, response, self._solution) + return QueuePage(self._version, response, solution=self._solution) def get(self, sid: str) -> QueueContext: """ diff --git a/twilio/rest/api/v2010/account/queue/member.py b/twilio/rest/api/v2010/account/queue/member.py index 30ff4abbc7..540befbbbe 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "queue_sid": queue_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[MemberContext] = None @property @@ -93,6 +95,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, url: str, method: Union[str, object] = values.unset ) -> "MemberInstance": @@ -125,6 +145,38 @@ async def update_async( method=method, ) + def update_with_http_info( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + url=url, + method=method, + ) + + async def update_with_http_info_async( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + url=url, + method=method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,20 +214,30 @@ def __init__( ) ) - def fetch(self) -> MemberInstance: + def _fetch(self) -> tuple: """ - Fetch the MemberInstance + Internal helper for fetch operation - - :returns: The fetched MemberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() return MemberInstance( self._version, payload, @@ -184,22 +246,47 @@ def fetch(self) -> MemberInstance: call_sid=self._solution["call_sid"], ) - async def fetch_async(self) -> MemberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MemberInstance + Fetch the MemberInstance and return response metadata - :returns: The fetched MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -208,16 +295,29 @@ async def fetch_async(self) -> MemberInstance: call_sid=self._solution["call_sid"], ) - def update( - self, url: str, method: Union[str, object] = values.unset - ) -> MemberInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the MemberInstance + Asynchronous coroutine to fetch the MemberInstance and return response metadata - :param url: The absolute URL of the Queue resource. - :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. - :returns: The updated MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, url: str, method: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -232,10 +332,22 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + payload, _, _ = self._update(url=url, method=method) return MemberInstance( self._version, payload, @@ -244,16 +356,35 @@ def update( call_sid=self._solution["call_sid"], ) - async def update_async( + def update_with_http_info( self, url: str, method: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MemberInstance + Update the MemberInstance and return response metadata :param url: The absolute URL of the Queue resource. :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. - :returns: The updated MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(url=url, method=method) + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -268,10 +399,22 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async(url=url, method=method) return MemberInstance( self._version, payload, @@ -280,6 +423,27 @@ async def update_async( call_sid=self._solution["call_sid"], ) + async def update_with_http_info_async( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(url=url, method=method) + instance = MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -298,6 +462,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -386,6 +551,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -405,6 +620,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -431,6 +647,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -439,6 +656,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MemberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -470,7 +737,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -503,7 +770,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MemberPage: """ @@ -515,7 +852,7 @@ def get_page(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MemberPage: """ @@ -527,7 +864,7 @@ async def get_page_async(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) def get(self, call_sid: str) -> MemberContext: """ diff --git a/twilio/rest/api/v2010/account/recording/__init__.py b/twilio/rest/api/v2010/account/recording/__init__.py index ab5c1c8b7b..75af476b00 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,7 +58,7 @@ class Status(object): :ivar price: The one-time cost of creating the recording in the `price_unit` currency. :ivar price_unit: The currency used in the `price` property. Example: `USD`. :ivar status: - :ivar channels: The number of channels in the final recording file. Can be: `1` or `2`. + :ivar channels: The number of channels in the recording resource. For information on specifying the number of channels in the downloaded recording file, check out [Fetch a Recording’s media file](https://www.twilio.com/docs/voice/api/recording#download-dual-channel-media-file). :ivar source: :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. @@ -109,6 +110,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -145,6 +147,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch( self, include_soft_deleted: Union[bool, object] = values.unset ) -> "RecordingInstance": @@ -173,6 +193,34 @@ async def fetch_async( include_soft_deleted=include_soft_deleted, ) + def fetch_with_http_info( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_soft_deleted=include_soft_deleted, + ) + + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_soft_deleted=include_soft_deleted, + ) + @property def add_on_results(self) -> AddOnResultList: """ @@ -221,6 +269,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._add_on_results: Optional[AddOnResultList] = None self._transcriptions: Optional[TranscriptionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -228,10 +290,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -240,25 +324,28 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch( - self, include_soft_deleted: Union[bool, object] = values.unset - ) -> RecordingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RecordingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + def _fetch(self, include_soft_deleted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), } @@ -268,10 +355,21 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch(include_soft_deleted=include_soft_deleted) return RecordingInstance( self._version, payload, @@ -279,18 +377,38 @@ def fetch( sid=self._solution["sid"], ) - async def fetch_async( + def fetch_with_http_info( self, include_soft_deleted: Union[bool, object] = values.unset - ) -> RecordingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), } @@ -300,10 +418,23 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) return RecordingInstance( self._version, payload, @@ -311,6 +442,27 @@ async def fetch_async( sid=self._solution["sid"], ) + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def add_on_results(self) -> AddOnResultList: """ @@ -355,6 +507,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -476,6 +629,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created: Union[datetime, object] = values.unset, @@ -507,6 +748,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -551,6 +793,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -565,6 +808,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created: Union[datetime, object] = values.unset, @@ -614,7 +943,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -665,7 +994,113 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RecordingPage: """ @@ -677,7 +1112,7 @@ def get_page(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RecordingPage: """ @@ -689,7 +1124,7 @@ async def get_page_async(self, target_url: str) -> RecordingPage: :returns: Page of RecordingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RecordingPage(self._version, response, self._solution) + return RecordingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RecordingContext: """ diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py index 95296f3cc4..2104ab225d 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "reference_sid": reference_sid, "sid": sid or self.sid, } + self._context: Optional[AddOnResultContext] = None @property @@ -121,6 +123,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AddOnResultInstance": """ Fetch the AddOnResultInstance @@ -139,6 +159,24 @@ async def fetch_async(self) -> "AddOnResultInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def payloads(self) -> PayloadList: """ @@ -183,6 +221,20 @@ def __init__( self._payloads: Optional[PayloadList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AddOnResultInstance @@ -190,10 +242,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddOnResultInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -202,27 +276,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AddOnResultInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AddOnResultInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AddOnResultInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AddOnResultInstance: + """ + Fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + payload, _, _ = self._fetch() return AddOnResultInstance( self._version, payload, @@ -231,22 +321,47 @@ def fetch(self) -> AddOnResultInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AddOnResultInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AddOnResultInstance + Fetch the AddOnResultInstance and return response metadata - :returns: The fetched AddOnResultInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AddOnResultInstance: + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + payload, _, _ = await self._fetch_async() return AddOnResultInstance( self._version, payload, @@ -255,6 +370,23 @@ async def fetch_async(self) -> AddOnResultInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddOnResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def payloads(self) -> PayloadList: """ @@ -287,6 +419,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: :param payload: Payload response from the API """ + return AddOnResultInstance( self._version, payload, @@ -375,6 +508,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -394,6 +577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -420,6 +604,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -428,6 +613,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AddOnResultInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -459,7 +694,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AddOnResultPage(self._version, response, self._solution) + return AddOnResultPage(self._version, response, solution=self._solution) async def page_async( self, @@ -492,7 +727,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AddOnResultPage(self._version, response, self._solution) + return AddOnResultPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddOnResultPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddOnResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddOnResultPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddOnResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AddOnResultPage: """ @@ -504,7 +809,7 @@ def get_page(self, target_url: str) -> AddOnResultPage: :returns: Page of AddOnResultInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AddOnResultPage(self._version, response, self._solution) + return AddOnResultPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AddOnResultPage: """ @@ -516,7 +821,7 @@ async def get_page_async(self, target_url: str) -> AddOnResultPage: :returns: Page of AddOnResultInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AddOnResultPage(self._version, response, self._solution) + return AddOnResultPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AddOnResultContext: """ diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py index 08e6ea2109..cabc10f323 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "add_on_result_sid": add_on_result_sid, "sid": sid or self.sid, } + self._context: Optional[PayloadContext] = None @property @@ -113,6 +115,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PayloadInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PayloadInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PayloadInstance": """ Fetch the PayloadInstance @@ -131,6 +151,24 @@ async def fetch_async(self) -> "PayloadInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PayloadInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PayloadInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def data(self) -> DataList: """ @@ -182,6 +220,20 @@ def __init__( self._data: Optional[DataList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PayloadInstance @@ -189,10 +241,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PayloadInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -201,27 +275,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PayloadInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PayloadInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PayloadInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PayloadInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PayloadInstance: + """ + Fetch the PayloadInstance + + :returns: The fetched PayloadInstance + """ + payload, _, _ = self._fetch() return PayloadInstance( self._version, payload, @@ -231,22 +321,48 @@ def fetch(self) -> PayloadInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> PayloadInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PayloadInstance + Fetch the PayloadInstance and return response metadata - :returns: The fetched PayloadInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PayloadInstance: + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + payload, _, _ = await self._fetch_async() return PayloadInstance( self._version, payload, @@ -256,6 +372,24 @@ async def fetch_async(self) -> PayloadInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PayloadInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def data(self) -> DataList: """ @@ -289,6 +423,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: :param payload: Payload response from the API """ + return PayloadInstance( self._version, payload, @@ -386,6 +521,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -405,6 +590,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -431,6 +617,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -439,6 +626,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PayloadInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -470,7 +707,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PayloadPage(self._version, response, self._solution) + return PayloadPage(self._version, response, solution=self._solution) async def page_async( self, @@ -503,7 +740,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PayloadPage(self._version, response, self._solution) + return PayloadPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PayloadPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PayloadPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PayloadPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PayloadPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PayloadPage: """ @@ -515,7 +822,7 @@ def get_page(self, target_url: str) -> PayloadPage: :returns: Page of PayloadInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PayloadPage(self._version, response, self._solution) + return PayloadPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PayloadPage: """ @@ -527,7 +834,7 @@ async def get_page_async(self, target_url: str) -> PayloadPage: :returns: Page of PayloadInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PayloadPage(self._version, response, self._solution) + return PayloadPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PayloadContext: """ diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py index 48567badca..e0847813c0 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( "add_on_result_sid": add_on_result_sid, "payload_sid": payload_sid, } + self._context: Optional[DataContext] = None @property @@ -82,6 +84,24 @@ async def fetch_async(self) -> "DataInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -124,20 +144,30 @@ def __init__( **self._solution ) - def fetch(self) -> DataInstance: + def _fetch(self) -> tuple: """ - Fetch the DataInstance - + Internal helper for fetch operation - :returns: The fetched DataInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DataInstance: + """ + Fetch the DataInstance + + :returns: The fetched DataInstance + """ + payload, _, _ = self._fetch() return DataInstance( self._version, payload, @@ -147,22 +177,48 @@ def fetch(self) -> DataInstance: payload_sid=self._solution["payload_sid"], ) - async def fetch_async(self) -> DataInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DataInstance + Fetch the DataInstance and return response metadata - :returns: The fetched DataInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DataInstance: + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + payload, _, _ = await self._fetch_async() return DataInstance( self._version, payload, @@ -172,6 +228,24 @@ async def fetch_async(self) -> DataInstance: payload_sid=self._solution["payload_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/recording/transcription.py b/twilio/rest/api/v2010/account/recording/transcription.py index 472f5b2bff..166d49f641 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "recording_sid": recording_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptionInstance": """ Fetch the TranscriptionInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "TranscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -168,6 +206,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptionInstance @@ -175,10 +227,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -187,27 +261,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TranscriptionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TranscriptionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TranscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = self._fetch() return TranscriptionInstance( self._version, payload, @@ -216,22 +306,47 @@ def fetch(self) -> TranscriptionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TranscriptionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TranscriptionInstance + Fetch the TranscriptionInstance and return response metadata - :returns: The fetched TranscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() return TranscriptionInstance( self._version, payload, @@ -240,6 +355,23 @@ async def fetch_async(self) -> TranscriptionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -258,6 +390,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, @@ -346,6 +479,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -365,6 +548,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -391,6 +575,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -399,6 +584,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -430,7 +665,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -463,7 +698,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TranscriptionPage: """ @@ -475,7 +780,7 @@ def get_page(self, target_url: str) -> TranscriptionPage: :returns: Page of TranscriptionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TranscriptionPage: """ @@ -487,7 +792,7 @@ async def get_page_async(self, target_url: str) -> TranscriptionPage: :returns: Page of TranscriptionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TranscriptionContext: """ diff --git a/twilio/rest/api/v2010/account/short_code.py b/twilio/rest/api/v2010/account/short_code.py index eae35c4aa5..c1c2e3f689 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "ShortCodeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -164,6 +184,66 @@ async def update_async( sms_fallback_method=sms_fallback_method, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ShortCodeInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ShortCodeInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -195,20 +275,30 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) - def fetch(self) -> ShortCodeInstance: + def _fetch(self) -> tuple: """ - Fetch the ShortCodeInstance - + Internal helper for fetch operation - :returns: The fetched ShortCodeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = self._fetch() return ShortCodeInstance( self._version, payload, @@ -216,22 +306,46 @@ def fetch(self) -> ShortCodeInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ShortCodeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ShortCodeInstance + Fetch the ShortCodeInstance and return response metadata - :returns: The fetched ShortCodeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = await self._fetch_async() return ShortCodeInstance( self._version, payload, @@ -239,7 +353,23 @@ async def fetch_async(self) -> ShortCodeInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -247,18 +377,12 @@ def update( sms_method: Union[str, object] = values.unset, sms_fallback_url: Union[str, object] = values.unset, sms_fallback_method: Union[str, object] = values.unset, - ) -> ShortCodeInstance: + ) -> tuple: """ - Update the ShortCodeInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. - :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. - :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. - :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. - :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. - :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. - - :returns: The updated ShortCodeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -277,10 +401,39 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) return ShortCodeInstance( self._version, payload, @@ -288,7 +441,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -296,9 +449,9 @@ async def update_async( sms_method: Union[str, object] = values.unset, sms_fallback_url: Union[str, object] = values.unset, sms_fallback_method: Union[str, object] = values.unset, - ) -> ShortCodeInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ShortCodeInstance + Update the ShortCodeInstance and return response metadata :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. @@ -307,7 +460,38 @@ async def update_async( :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. - :returns: The updated ShortCodeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,10 +510,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) return ShortCodeInstance( self._version, payload, @@ -337,6 +550,43 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ShortCodeInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + instance = ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -355,6 +605,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: :param payload: Payload response from the API """ + return ShortCodeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -454,6 +705,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ShortCodeInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ShortCodeInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -477,6 +792,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -509,6 +825,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -519,6 +836,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ShortCodeInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ShortCodeInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -556,7 +935,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) async def page_async( self, @@ -595,7 +974,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ShortCodePage: """ @@ -607,7 +1068,7 @@ def get_page(self, target_url: str) -> ShortCodePage: :returns: Page of ShortCodeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ShortCodePage: """ @@ -619,7 +1080,7 @@ async def get_page_async(self, target_url: str) -> ShortCodePage: :returns: Page of ShortCodeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) def get(self, sid: str) -> ShortCodeContext: """ diff --git a/twilio/rest/api/v2010/account/signing_key.py b/twilio/rest/api/v2010/account/signing_key.py index 8e33f218f5..64ba733192 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[SigningKeyContext] = None @property @@ -88,6 +90,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SigningKeyInstance": """ Fetch the SigningKeyInstance @@ -106,6 +126,24 @@ async def fetch_async(self) -> "SigningKeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "SigningKeyInstance": @@ -134,6 +172,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SigningKeyInstance with HTTP info + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SigningKeyInstance with HTTP info + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,6 +231,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SigningKeyInstance @@ -172,10 +252,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SigningKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -184,27 +286,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SigningKeyInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SigningKeyInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SigningKeyInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SigningKeyInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SigningKeyInstance: + """ + Fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + payload, _, _ = self._fetch() return SigningKeyInstance( self._version, payload, @@ -212,22 +330,46 @@ def fetch(self) -> SigningKeyInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SigningKeyInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SigningKeyInstance + Fetch the SigningKeyInstance and return response metadata - :returns: The fetched SigningKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SigningKeyInstance: + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + payload, _, _ = await self._fetch_async() return SigningKeyInstance( self._version, payload, @@ -235,15 +377,28 @@ async def fetch_async(self) -> SigningKeyInstance: sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> SigningKeyInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SigningKeyInstance + Asynchronous coroutine to fetch the SigningKeyInstance and return response metadata - :param friendly_name: - :returns: The updated SigningKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -257,10 +412,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return SigningKeyInstance( self._version, payload, @@ -268,15 +434,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> SigningKeyInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SigningKeyInstance + Update the SigningKeyInstance and return response metadata :param friendly_name: - :returns: The updated SigningKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -290,10 +474,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return SigningKeyInstance( self._version, payload, @@ -301,6 +496,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SigningKeyInstance and return response metadata + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -319,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: :param payload: Payload response from the API """ + return SigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -400,6 +617,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -419,6 +686,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -445,6 +713,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -453,6 +722,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SigningKeyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -484,7 +803,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SigningKeyPage(self._version, response, self._solution) + return SigningKeyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -517,7 +836,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SigningKeyPage(self._version, response, self._solution) + return SigningKeyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SigningKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SigningKeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SigningKeyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SigningKeyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SigningKeyPage: """ @@ -529,7 +918,7 @@ def get_page(self, target_url: str) -> SigningKeyPage: :returns: Page of SigningKeyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SigningKeyPage(self._version, response, self._solution) + return SigningKeyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SigningKeyPage: """ @@ -541,7 +930,7 @@ async def get_page_async(self, target_url: str) -> SigningKeyPage: :returns: Page of SigningKeyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SigningKeyPage(self._version, response, self._solution) + return SigningKeyPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SigningKeyContext: """ diff --git a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py index d1be747b6d..0aef74f3b0 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListInstance": """ Fetch the CredentialListInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "CredentialListInstance": """ Update the CredentialListInstance @@ -139,6 +177,30 @@ async def update_async(self, friendly_name: str) -> "CredentialListInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the CredentialListInstance with HTTP info + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialListInstance with HTTP info + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def credentials(self) -> CredentialList: """ @@ -179,6 +241,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._credentials: Optional[CredentialList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListInstance @@ -186,10 +262,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -198,27 +296,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialListInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialListInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = self._fetch() return CredentialListInstance( self._version, payload, @@ -226,22 +340,46 @@ def fetch(self) -> CredentialListInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialListInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialListInstance + Fetch the CredentialListInstance and return response metadata - :returns: The fetched CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = await self._fetch_async() return CredentialListInstance( self._version, payload, @@ -249,13 +387,28 @@ async def fetch_async(self) -> CredentialListInstance: sid=self._solution["sid"], ) - def update(self, friendly_name: str) -> CredentialListInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the CredentialListInstance + Asynchronous coroutine to fetch the CredentialListInstance and return response metadata - :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: The updated CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -269,10 +422,19 @@ def update(self, friendly_name: str) -> CredentialListInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: str) -> CredentialListInstance: + """ + Update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return CredentialListInstance( self._version, payload, @@ -280,13 +442,29 @@ def update(self, friendly_name: str) -> CredentialListInstance: sid=self._solution["sid"], ) - async def update_async(self, friendly_name: str) -> CredentialListInstance: + def update_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronous coroutine to update the CredentialListInstance + Update the CredentialListInstance and return response metadata :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. - :returns: The updated CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -300,10 +478,19 @@ async def update_async(self, friendly_name: str) -> CredentialListInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return CredentialListInstance( self._version, payload, @@ -311,6 +498,25 @@ async def update_async(self, friendly_name: str) -> CredentialListInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialListInstance and return response metadata + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def credentials(self) -> CredentialList: """ @@ -342,6 +548,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -375,13 +582,12 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create(self, friendly_name: str) -> CredentialListInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the CredentialListInstance - - :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + Internal helper for create operation - :returns: The created CredentialListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -395,21 +601,43 @@ def create(self, friendly_name: str) -> CredentialListInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return CredentialListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async(self, friendly_name: str) -> CredentialListInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the CredentialListInstance + Create the CredentialListInstance and return response metadata :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. - :returns: The created CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -423,14 +651,39 @@ async def create_async(self, friendly_name: str) -> CredentialListInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return CredentialListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the CredentialListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -481,6 +734,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -500,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -526,6 +830,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -534,6 +839,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -565,7 +920,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -598,7 +953,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CredentialListPage: """ @@ -610,7 +1035,7 @@ def get_page(self, target_url: str) -> CredentialListPage: :returns: Page of CredentialListInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> CredentialListPage: """ @@ -622,7 +1047,7 @@ async def get_page_async(self, target_url: str) -> CredentialListPage: :returns: Page of CredentialListInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) def get(self, sid: str) -> CredentialListContext: """ diff --git a/twilio/rest/api/v2010/account/sip/credential_list/credential.py b/twilio/rest/api/v2010/account/sip/credential_list/credential.py index 9c52a110e0..2a237527f2 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/credential.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "credential_list_sid": credential_list_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, password: Union[str, object] = values.unset ) -> "CredentialInstance": @@ -143,6 +181,34 @@ async def update_async( password=password, ) + def update_with_http_info( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + password=password, + ) + + async def update_with_http_info_async( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + password=password, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -178,6 +244,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -185,10 +265,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -197,27 +299,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, @@ -226,22 +344,47 @@ def fetch(self) -> CredentialInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, @@ -250,13 +393,29 @@ async def fetch_async(self) -> CredentialInstance: sid=self._solution["sid"], ) - def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the CredentialInstance + Asynchronous coroutine to fetch the CredentialInstance and return response metadata - :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) - :returns: The updated CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, password: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -270,10 +429,19 @@ def update(self, password: Union[str, object] = values.unset) -> CredentialInsta headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + payload, _, _ = self._update(password=password) return CredentialInstance( self._version, payload, @@ -282,15 +450,32 @@ def update(self, password: Union[str, object] = values.unset) -> CredentialInsta sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, password: Union[str, object] = values.unset - ) -> CredentialInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance and return response metadata :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) - :returns: The updated CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(password=password) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, password: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -304,10 +489,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, password: Union[str, object] = values.unset + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async(password=password) return CredentialInstance( self._version, payload, @@ -316,6 +512,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(password=password) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -334,6 +550,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance( self._version, payload, @@ -372,14 +589,12 @@ def __init__(self, version: Version, account_sid: str, credential_list_sid: str) **self._solution ) - def create(self, username: str, password: str) -> CredentialInstance: + def _create(self, username: str, password: str) -> tuple: """ - Create the CredentialInstance - - :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. - :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -394,10 +609,20 @@ def create(self, username: str, password: str) -> CredentialInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, username: str, password: str) -> CredentialInstance: + """ + Create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + payload, _, _ = self._create(username=username, password=password) return CredentialInstance( self._version, payload, @@ -405,14 +630,32 @@ def create(self, username: str, password: str) -> CredentialInstance: credential_list_sid=self._solution["credential_list_sid"], ) - async def create_async(self, username: str, password: str) -> CredentialInstance: + def create_with_http_info(self, username: str, password: str) -> ApiResponse: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance and return response metadata :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) - :returns: The created CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + username=username, password=password + ) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, username: str, password: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -427,10 +670,20 @@ async def create_async(self, username: str, password: str) -> CredentialInstance headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, username: str, password: str) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async(username=username, password=password) return CredentialInstance( self._version, payload, @@ -438,6 +691,28 @@ async def create_async(self, username: str, password: str) -> CredentialInstance credential_list_sid=self._solution["credential_list_sid"], ) + async def create_with_http_info_async( + self, username: str, password: str + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + username=username, password=password + ) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -488,6 +763,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -507,6 +832,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -533,6 +859,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -541,6 +868,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -572,7 +949,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialPage(self._version, response, self._solution) + return CredentialPage(self._version, response, solution=self._solution) async def page_async( self, @@ -605,7 +982,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialPage(self._version, response, self._solution) + return CredentialPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CredentialPage: """ @@ -617,7 +1064,7 @@ def get_page(self, target_url: str) -> CredentialPage: :returns: Page of CredentialInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CredentialPage(self._version, response, self._solution) + return CredentialPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> CredentialPage: """ @@ -629,7 +1076,7 @@ async def get_page_async(self, target_url: str) -> CredentialPage: :returns: Page of CredentialInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CredentialPage(self._version, response, self._solution) + return CredentialPage(self._version, response, solution=self._solution) def get(self, sid: str) -> CredentialContext: """ diff --git a/twilio/rest/api/v2010/account/sip/domain/__init__.py b/twilio/rest/api/v2010/account/sip/domain/__init__.py index 0a45e68273..3b8f3f32e9 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[DomainContext] = None @property @@ -137,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DomainInstance": """ Fetch the DomainInstance @@ -155,6 +175,24 @@ async def fetch_async(self) -> "DomainInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -257,6 +295,108 @@ async def update_async( emergency_caller_sid=emergency_caller_sid, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the DomainInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + @property def auth(self) -> AuthTypesList: """ @@ -315,6 +455,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): IpAccessControlListMappingList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DomainInstance @@ -322,10 +476,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -334,27 +510,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> DomainInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the DomainInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched DomainInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainInstance: + """ + Fetch the DomainInstance + + :returns: The fetched DomainInstance + """ + payload, _, _ = self._fetch() return DomainInstance( self._version, payload, @@ -362,22 +554,46 @@ def fetch(self) -> DomainInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> DomainInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DomainInstance + Fetch the DomainInstance and return response metadata - :returns: The fetched DomainInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DomainInstance: + """ + Asynchronous coroutine to fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + payload, _, _ = await self._fetch_async() return DomainInstance( self._version, payload, @@ -385,7 +601,23 @@ async def fetch_async(self) -> DomainInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, voice_fallback_method: Union[str, object] = values.unset, @@ -400,25 +632,12 @@ def update( secure: Union[bool, object] = values.unset, byoc_trunk_sid: Union[str, object] = values.unset, emergency_caller_sid: Union[str, object] = values.unset, - ) -> DomainInstance: + ) -> tuple: """ - Update the DomainInstance - - :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. - :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. - :param voice_method: The HTTP method we should use to call `voice_url` - :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. - :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. - :param voice_url: The URL we should call when the domain receives a call. - :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. - :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. - :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. - :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. - :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. - :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + Internal helper for update operation - :returns: The updated DomainInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -446,18 +665,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return DomainInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, voice_fallback_method: Union[str, object] = values.unset, @@ -474,7 +686,7 @@ async def update_async( emergency_caller_sid: Union[str, object] = values.unset, ) -> DomainInstance: """ - Asynchronous coroutine to update the DomainInstance + Update the DomainInstance :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. @@ -492,36 +704,21 @@ async def update_async( :returns: The updated DomainInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceStatusCallbackMethod": voice_status_callback_method, - "VoiceStatusCallbackUrl": voice_status_callback_url, - "VoiceUrl": voice_url, - "SipRegistration": serialize.boolean_to_string(sip_registration), - "DomainName": domain_name, - "EmergencyCallingEnabled": serialize.boolean_to_string( - emergency_calling_enabled - ), - "Secure": serialize.boolean_to_string(secure), - "ByocTrunkSid": byoc_trunk_sid, - "EmergencyCallerSid": emergency_caller_sid, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, ) - return DomainInstance( self._version, payload, @@ -529,13 +726,238 @@ async def update_async( sid=self._solution["sid"], ) - @property - def auth(self) -> AuthTypesList: - """ - Access the auth - """ - if self._auth is None: - self._auth = AuthTypesList( + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the DomainInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def auth(self) -> AuthTypesList: + """ + Access the auth + """ + if self._auth is None: + self._auth = AuthTypesList( self._version, self._solution["account_sid"], self._solution["sid"], @@ -586,6 +1008,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: :param payload: Payload response from the API """ + return DomainInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -617,7 +1040,113 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/SIP/Domains.json".format(**self._solution) - def create( + def _create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "DomainName": domain_name, + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + payload, _, _ = self._create( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( self, domain_name: str, friendly_name: Union[str, object] = values.unset, @@ -632,9 +1161,9 @@ def create( secure: Union[bool, object] = values.unset, byoc_trunk_sid: Union[str, object] = values.unset, emergency_caller_sid: Union[str, object] = values.unset, - ) -> DomainInstance: + ) -> ApiResponse: """ - Create the DomainInstance + Create the DomainInstance and return response metadata :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. @@ -650,7 +1179,49 @@ def create( :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. - :returns: The created DomainInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -678,14 +1249,10 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return DomainInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - async def create_async( self, domain_name: str, @@ -721,39 +1288,79 @@ async def create_async( :returns: The created DomainInstance """ - - data = values.of( - { - "DomainName": domain_name, - "FriendlyName": friendly_name, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceStatusCallbackUrl": voice_status_callback_url, - "VoiceStatusCallbackMethod": voice_status_callback_method, - "SipRegistration": serialize.boolean_to_string(sip_registration), - "EmergencyCallingEnabled": serialize.boolean_to_string( - emergency_calling_enabled - ), - "Secure": serialize.boolean_to_string(secure), - "ByocTrunkSid": byoc_trunk_sid, - "EmergencyCallerSid": emergency_caller_sid, - } + payload, _, _ = await self._create_async( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def create_with_http_info_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the DomainInstance and return response metadata - headers["Accept"] = "application/json" + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, ) - - return DomainInstance( + instance = DomainInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -805,6 +1412,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -824,6 +1481,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -850,6 +1508,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -858,6 +1517,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DomainInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -889,7 +1598,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DomainPage(self._version, response, self._solution) + return DomainPage(self._version, response, solution=self._solution) async def page_async( self, @@ -922,7 +1631,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DomainPage(self._version, response, self._solution) + return DomainPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DomainPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DomainPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DomainPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DomainPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DomainPage: """ @@ -934,7 +1713,7 @@ def get_page(self, target_url: str) -> DomainPage: :returns: Page of DomainInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DomainPage(self._version, response, self._solution) + return DomainPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DomainPage: """ @@ -946,7 +1725,7 @@ async def get_page_async(self, target_url: str) -> DomainPage: :returns: Page of DomainInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DomainPage(self._version, response, self._solution) + return DomainPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DomainContext: """ diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py index 4839f17d48..0e539d09c6 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsCredentialListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthCallsCredentialListMappingInstance": """ Fetch the AuthCallsCredentialListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthCallsCredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,6 +184,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthCallsCredentialListMappingInstance @@ -153,10 +205,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -165,27 +239,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AuthCallsCredentialListMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AuthCallsCredentialListMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AuthCallsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsCredentialListMappingInstance: + """ + Fetch the AuthCallsCredentialListMappingInstance + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + payload, _, _ = self._fetch() return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -194,22 +284,47 @@ def fetch(self) -> AuthCallsCredentialListMappingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + Fetch the AuthCallsCredentialListMappingInstance and return response metadata - :returns: The fetched AuthCallsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + payload, _, _ = await self._fetch_async() return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -218,6 +333,23 @@ async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -278,15 +411,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, credential_list_sid: str - ) -> AuthCallsCredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the AuthCallsCredentialListMappingInstance + Internal helper for create operation - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - - :returns: The created AuthCallsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -300,10 +430,21 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -311,15 +452,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> AuthCallsCredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthCallsCredentialListMappingInstance + Create the AuthCallsCredentialListMappingInstance and return response metadata :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - :returns: The created AuthCallsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -333,10 +490,23 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronously create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -344,6 +514,27 @@ async def create_async( domain_sid=self._solution["domain_sid"], ) + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthCallsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -394,6 +585,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -413,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -439,6 +681,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -447,6 +690,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthCallsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -479,7 +772,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return AuthCallsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -514,8 +807,82 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return AuthCallsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthCallsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthCallsCredentialListMappingPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AuthCallsCredentialListMappingPage: """ @@ -528,7 +895,7 @@ def get_page(self, target_url: str) -> AuthCallsCredentialListMappingPage: """ response = self._version.domain.twilio.request("GET", target_url) return AuthCallsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -544,7 +911,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return AuthCallsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> AuthCallsCredentialListMappingContext: diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py index 198f4fc406..d8a7aba9a7 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsIpAccessControlListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthCallsIpAccessControlListMappingInstance": """ Fetch the AuthCallsIpAccessControlListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthCallsIpAccessControlListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,6 +186,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthCallsIpAccessControlListMappingInstance @@ -155,10 +207,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -167,27 +241,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AuthCallsIpAccessControlListMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AuthCallsIpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = self._fetch() return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -196,22 +286,47 @@ def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + Fetch the AuthCallsIpAccessControlListMappingInstance and return response metadata - :returns: The fetched AuthCallsIpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = await self._fetch_async() return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -220,6 +335,23 @@ async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -244,6 +376,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -282,15 +415,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, ip_access_control_list_sid: str - ) -> AuthCallsIpAccessControlListMappingInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the AuthCallsIpAccessControlListMappingInstance + Internal helper for create operation - :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. - - :returns: The created AuthCallsIpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -304,10 +434,23 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -315,15 +458,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> AuthCallsIpAccessControlListMappingInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthCallsIpAccessControlListMappingInstance + Create the AuthCallsIpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. - :returns: The created AuthCallsIpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -337,10 +496,23 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronously create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -348,6 +520,27 @@ async def create_async( domain_sid=self._solution["domain_sid"], ) + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthCallsIpAccessControlListMappingInstance and return response metadata + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -398,6 +591,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -417,6 +660,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -443,6 +687,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -451,6 +696,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthCallsIpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -483,7 +778,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -518,8 +813,82 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsIpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthCallsIpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthCallsIpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthCallsIpAccessControlListMappingPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AuthCallsIpAccessControlListMappingPage: """ @@ -532,7 +901,7 @@ def get_page(self, target_url: str) -> AuthCallsIpAccessControlListMappingPage: """ response = self._version.domain.twilio.request("GET", target_url) return AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -548,7 +917,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py index e4b1bf0d23..78671458dc 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthRegistrationsCredentialListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthRegistrationsCredentialListMappingInstance": """ Fetch the AuthRegistrationsCredentialListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthRegistrationsCredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,6 +184,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthRegistrationsCredentialListMappingInstance @@ -153,10 +205,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -165,27 +239,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AuthRegistrationsCredentialListMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AuthRegistrationsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = self._fetch() return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -194,22 +284,47 @@ def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + Fetch the AuthRegistrationsCredentialListMappingInstance and return response metadata - :returns: The fetched AuthRegistrationsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = await self._fetch_async() return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -218,6 +333,23 @@ async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -278,15 +411,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, credential_list_sid: str - ) -> AuthRegistrationsCredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the AuthRegistrationsCredentialListMappingInstance + Internal helper for create operation - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - - :returns: The created AuthRegistrationsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -300,10 +430,21 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -311,15 +452,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> AuthRegistrationsCredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthRegistrationsCredentialListMappingInstance + Create the AuthRegistrationsCredentialListMappingInstance and return response metadata :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - :returns: The created AuthRegistrationsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -333,10 +490,23 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronously create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -344,6 +514,27 @@ async def create_async( domain_sid=self._solution["domain_sid"], ) + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the AuthRegistrationsCredentialListMappingInstance and return response metadata + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -394,6 +585,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -413,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -439,6 +681,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -447,6 +690,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthRegistrationsCredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -479,7 +772,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return AuthRegistrationsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -514,8 +807,82 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return AuthRegistrationsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthRegistrationsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthRegistrationsCredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthRegistrationsCredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthRegistrationsCredentialListMappingPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AuthRegistrationsCredentialListMappingPage: """ @@ -528,7 +895,7 @@ def get_page(self, target_url: str) -> AuthRegistrationsCredentialListMappingPag """ response = self._version.domain.twilio.request("GET", target_url) return AuthRegistrationsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -544,7 +911,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return AuthRegistrationsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> AuthRegistrationsCredentialListMappingContext: diff --git a/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py index b520f4813a..cbdbc3e470 100644 --- a/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListMappingContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListMappingInstance": """ Fetch the CredentialListMappingInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,6 +186,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListMappingInstance @@ -155,10 +207,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -167,27 +241,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialListMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialListMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListMappingInstance: + """ + Fetch the CredentialListMappingInstance + + :returns: The fetched CredentialListMappingInstance + """ + payload, _, _ = self._fetch() return CredentialListMappingInstance( self._version, payload, @@ -196,22 +286,47 @@ def fetch(self) -> CredentialListMappingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialListMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialListMappingInstance + Fetch the CredentialListMappingInstance and return response metadata - :returns: The fetched CredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + payload, _, _ = await self._fetch_async() return CredentialListMappingInstance( self._version, payload, @@ -220,6 +335,23 @@ async def fetch_async(self) -> CredentialListMappingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -238,6 +370,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance :param payload: Payload response from the API """ + return CredentialListMappingInstance( self._version, payload, @@ -276,13 +409,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the CredentialListMappingInstance - - :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + Internal helper for create operation - :returns: The created CredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,10 +428,19 @@ def create(self, credential_list_sid: str) -> CredentialListMappingInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + """ + Create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) return CredentialListMappingInstance( self._version, payload, @@ -307,15 +448,31 @@ def create(self, credential_list_sid: str) -> CredentialListMappingInstance: domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> CredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the CredentialListMappingInstance + Create the CredentialListMappingInstance and return response metadata :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. - :returns: The created CredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +486,23 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, credential_list_sid: str + ) -> CredentialListMappingInstance: + """ + Asynchronously create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) return CredentialListMappingInstance( self._version, payload, @@ -340,6 +510,27 @@ async def create_async( domain_sid=self._solution["domain_sid"], ) + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the CredentialListMappingInstance and return response metadata + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -390,6 +581,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -409,6 +650,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -435,6 +677,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -443,6 +686,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -474,7 +767,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListMappingPage(self._version, response, self._solution) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -507,7 +802,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListMappingPage(self._version, response, self._solution) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CredentialListMappingPage: """ @@ -519,7 +890,9 @@ def get_page(self, target_url: str) -> CredentialListMappingPage: :returns: Page of CredentialListMappingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CredentialListMappingPage(self._version, response, self._solution) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> CredentialListMappingPage: """ @@ -531,7 +904,9 @@ async def get_page_async(self, target_url: str) -> CredentialListMappingPage: :returns: Page of CredentialListMappingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CredentialListMappingPage(self._version, response, self._solution) + return CredentialListMappingPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> CredentialListMappingContext: """ diff --git a/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py index 4dfecfe826..2a3c582b70 100644 --- a/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListMappingContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListMappingInstance": """ Fetch the IpAccessControlListMappingInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "IpAccessControlListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,6 +188,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListMappingInstance @@ -157,10 +209,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -169,27 +243,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IpAccessControlListMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IpAccessControlListMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListMappingInstance: + """ + Fetch the IpAccessControlListMappingInstance + + :returns: The fetched IpAccessControlListMappingInstance + """ + payload, _, _ = self._fetch() return IpAccessControlListMappingInstance( self._version, payload, @@ -198,22 +288,47 @@ def fetch(self) -> IpAccessControlListMappingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> IpAccessControlListMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + Fetch the IpAccessControlListMappingInstance and return response metadata - :returns: The fetched IpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + payload, _, _ = await self._fetch_async() return IpAccessControlListMappingInstance( self._version, payload, @@ -222,6 +337,23 @@ async def fetch_async(self) -> IpAccessControlListMappingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -242,6 +374,7 @@ def get_instance( :param payload: Payload response from the API """ + return IpAccessControlListMappingInstance( self._version, payload, @@ -280,15 +413,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListMappingInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the IpAccessControlListMappingInstance - - :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + Internal helper for create operation - :returns: The created IpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -302,10 +432,23 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListMappingInstance( self._version, payload, @@ -313,15 +456,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListMappingInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the IpAccessControlListMappingInstance + Create the IpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. - :returns: The created IpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -335,10 +494,23 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Asynchronously create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListMappingInstance( self._version, payload, @@ -346,6 +518,27 @@ async def create_async( domain_sid=self._solution["domain_sid"], ) + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListMappingInstance and return response metadata + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -396,6 +589,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -415,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -441,6 +685,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -449,6 +694,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpAccessControlListMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -480,7 +775,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListMappingPage(self._version, response, self._solution) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -513,7 +810,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListMappingPage(self._version, response, self._solution) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IpAccessControlListMappingPage: """ @@ -525,7 +898,9 @@ def get_page(self, target_url: str) -> IpAccessControlListMappingPage: :returns: Page of IpAccessControlListMappingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return IpAccessControlListMappingPage(self._version, response, self._solution) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPage: """ @@ -537,7 +912,9 @@ async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPag :returns: Page of IpAccessControlListMappingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return IpAccessControlListMappingPage(self._version, response, self._solution) + return IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> IpAccessControlListMappingContext: """ diff --git a/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py b/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py index afa504c208..e2161d40ae 100644 --- a/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListInstance": """ Fetch the IpAccessControlListInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "IpAccessControlListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "IpAccessControlListInstance": """ Update the IpAccessControlListInstance @@ -141,6 +179,30 @@ async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the IpAccessControlListInstance with HTTP info + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAccessControlListInstance with HTTP info + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def ip_addresses(self) -> IpAddressList: """ @@ -183,6 +245,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._ip_addresses: Optional[IpAddressList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListInstance @@ -190,10 +266,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -202,27 +300,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IpAccessControlListInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IpAccessControlListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + payload, _, _ = self._fetch() return IpAccessControlListInstance( self._version, payload, @@ -230,22 +344,46 @@ def fetch(self) -> IpAccessControlListInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> IpAccessControlListInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpAccessControlListInstance + Fetch the IpAccessControlListInstance and return response metadata - :returns: The fetched IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + payload, _, _ = await self._fetch_async() return IpAccessControlListInstance( self._version, payload, @@ -253,13 +391,28 @@ async def fetch_async(self) -> IpAccessControlListInstance: sid=self._solution["sid"], ) - def update(self, friendly_name: str) -> IpAccessControlListInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the IpAccessControlListInstance + Asynchronous coroutine to fetch the IpAccessControlListInstance and return response metadata - :param friendly_name: A human readable descriptive text, up to 255 characters long. - :returns: The updated IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -273,10 +426,19 @@ def update(self, friendly_name: str) -> IpAccessControlListInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return IpAccessControlListInstance( self._version, payload, @@ -284,13 +446,29 @@ def update(self, friendly_name: str) -> IpAccessControlListInstance: sid=self._solution["sid"], ) - async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: + def update_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronous coroutine to update the IpAccessControlListInstance + Update the IpAccessControlListInstance and return response metadata :param friendly_name: A human readable descriptive text, up to 255 characters long. - :returns: The updated IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -304,10 +482,19 @@ async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return IpAccessControlListInstance( self._version, payload, @@ -315,6 +502,25 @@ async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAccessControlListInstance and return response metadata + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def ip_addresses(self) -> IpAddressList: """ @@ -346,6 +552,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -379,13 +586,12 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create(self, friendly_name: str) -> IpAccessControlListInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the IpAccessControlListInstance - - :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + Internal helper for create operation - :returns: The created IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -399,21 +605,43 @@ def create(self, friendly_name: str) -> IpAccessControlListInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return IpAccessControlListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the IpAccessControlListInstance + Create the IpAccessControlListInstance and return response metadata :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. - :returns: The created IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -427,14 +655,39 @@ async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return IpAccessControlListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListInstance and return response metadata + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -485,6 +738,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -504,6 +807,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -530,6 +834,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -538,6 +843,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -569,7 +924,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -602,7 +957,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IpAccessControlListPage: """ @@ -614,7 +1039,7 @@ def get_page(self, target_url: str) -> IpAccessControlListPage: :returns: Page of IpAccessControlListInstance """ response = self._version.domain.twilio.request("GET", target_url) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> IpAccessControlListPage: """ @@ -626,7 +1051,7 @@ async def get_page_async(self, target_url: str) -> IpAccessControlListPage: :returns: Page of IpAccessControlListInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) def get(self, sid: str) -> IpAccessControlListContext: """ diff --git a/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py b/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py index ca2f82eacc..aefcad2b39 100644 --- a/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "ip_access_control_list_sid": ip_access_control_list_sid, "sid": sid or self.sid, } + self._context: Optional[IpAddressContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAddressInstance": """ Fetch the IpAddressInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "IpAddressInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ip_address: Union[str, object] = values.unset, @@ -165,6 +203,48 @@ async def update_async( cidr_prefix_length=cidr_prefix_length, ) + def update_with_http_info( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the IpAddressInstance with HTTP info + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_with_http_info_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAddressInstance with HTTP info + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -204,6 +284,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAddressInstance @@ -211,10 +305,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAddressInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -223,27 +339,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAddressInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IpAddressInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IpAddressInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IpAddressInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAddressInstance: + """ + Fetch the IpAddressInstance + + :returns: The fetched IpAddressInstance + """ + payload, _, _ = self._fetch() return IpAddressInstance( self._version, payload, @@ -252,22 +384,47 @@ def fetch(self) -> IpAddressInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> IpAddressInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpAddressInstance + Fetch the IpAddressInstance and return response metadata - :returns: The fetched IpAddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpAddressInstance: + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + payload, _, _ = await self._fetch_async() return IpAddressInstance( self._version, payload, @@ -276,20 +433,34 @@ async def fetch_async(self) -> IpAddressInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAddressInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, ip_address: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> tuple: """ - Update the IpAddressInstance + Internal helper for update operation - :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. - :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. - :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. - - :returns: The updated IpAddressInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -305,10 +476,30 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + payload, _, _ = self._update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) return IpAddressInstance( self._version, payload, @@ -317,20 +508,46 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, ip_address: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the IpAddressInstance + Update the IpAddressInstance and return response metadata :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. - :returns: The updated IpAddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -346,10 +563,30 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + payload, _, _ = await self._update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) return IpAddressInstance( self._version, payload, @@ -358,6 +595,35 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAddressInstance and return response metadata + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -376,6 +642,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: :param payload: Payload response from the API """ + return IpAddressInstance( self._version, payload, @@ -416,20 +683,17 @@ def __init__( **self._solution ) - def create( + def _create( self, friendly_name: str, ip_address: str, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> tuple: """ - Create the IpAddressInstance - - :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. - :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. - :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + Internal helper for create operation - :returns: The created IpAddressInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -445,10 +709,30 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) return IpAddressInstance( self._version, payload, @@ -456,20 +740,45 @@ def create( ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) - async def create_async( + def create_with_http_info( self, friendly_name: str, ip_address: str, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> ApiResponse: """ - Asynchronously create the IpAddressInstance + Create the IpAddressInstance and return response metadata :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. - :returns: The created IpAddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -485,10 +794,30 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronously create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) return IpAddressInstance( self._version, payload, @@ -496,6 +825,34 @@ async def create_async( ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) + async def create_with_http_info_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpAddressInstance and return response metadata + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -546,6 +903,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -565,6 +972,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -591,6 +999,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -599,6 +1008,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -630,7 +1089,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAddressPage(self._version, response, self._solution) + return IpAddressPage(self._version, response, solution=self._solution) async def page_async( self, @@ -663,7 +1122,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAddressPage(self._version, response, self._solution) + return IpAddressPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IpAddressPage: """ @@ -675,7 +1204,7 @@ def get_page(self, target_url: str) -> IpAddressPage: :returns: Page of IpAddressInstance """ response = self._version.domain.twilio.request("GET", target_url) - return IpAddressPage(self._version, response, self._solution) + return IpAddressPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> IpAddressPage: """ @@ -687,7 +1216,7 @@ async def get_page_async(self, target_url: str) -> IpAddressPage: :returns: Page of IpAddressInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return IpAddressPage(self._version, response, self._solution) + return IpAddressPage(self._version, response, solution=self._solution) def get(self, sid: str) -> IpAddressContext: """ diff --git a/twilio/rest/api/v2010/account/token.py b/twilio/rest/api/v2010/account/token.py index fa43360fb1..4cc10f7026 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,13 +80,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) - def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: + def _create(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Create the TokenInstance - - :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + Internal helper for create operation - :returns: The created TokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -99,23 +99,45 @@ def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: + """ + Create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + payload, _, _ = self._create(ttl=ttl) return TokenInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, ttl: Union[int, object] = values.unset - ) -> TokenInstance: + ) -> ApiResponse: """ - Asynchronously create the TokenInstance + Create the TokenInstance and return response metadata :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). - :returns: The created TokenInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(ttl=ttl) + instance = TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -129,14 +151,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async(ttl=ttl) return TokenInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(ttl=ttl) + instance = TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/transcription.py b/twilio/rest/api/v2010/account/transcription.py index 386ff9ee74..341c4ffdb3 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptionInstance": """ Fetch the TranscriptionInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "TranscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -161,6 +199,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptionInstance @@ -168,10 +220,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -180,27 +254,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TranscriptionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TranscriptionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TranscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = self._fetch() return TranscriptionInstance( self._version, payload, @@ -208,22 +298,46 @@ def fetch(self) -> TranscriptionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TranscriptionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TranscriptionInstance + Fetch the TranscriptionInstance and return response metadata - :returns: The fetched TranscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() return TranscriptionInstance( self._version, payload, @@ -231,6 +345,22 @@ async def fetch_async(self) -> TranscriptionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -249,6 +379,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -332,6 +463,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -351,6 +532,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -377,6 +559,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -385,6 +568,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -416,7 +649,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -449,7 +682,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TranscriptionPage: """ @@ -461,7 +764,7 @@ def get_page(self, target_url: str) -> TranscriptionPage: :returns: Page of TranscriptionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TranscriptionPage: """ @@ -473,7 +776,7 @@ async def get_page_async(self, target_url: str) -> TranscriptionPage: :returns: Page of TranscriptionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TranscriptionContext: """ diff --git a/twilio/rest/api/v2010/account/usage/record/__init__.py b/twilio/rest/api/v2010/account/usage/record/__init__.py index 1798eb4079..a721a595d3 100644 --- a/twilio/rest/api/v2010/account/usage/record/__init__.py +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,337 +32,11 @@ class RecordInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -381,7 +56,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["RecordInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -422,6 +97,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: :param payload: Payload response from the API """ + return RecordInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -466,7 +142,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -479,7 +155,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -505,7 +181,7 @@ def stream( async def stream_async( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -518,7 +194,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -542,9 +218,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RecordInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RecordInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -556,7 +308,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -569,6 +321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -582,7 +335,7 @@ def list( async def list_async( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -594,7 +347,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -607,6 +360,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -619,9 +373,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RecordInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RecordInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -662,11 +490,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordPage(self._version, response, self._solution) + return RecordPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["RecordInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -707,7 +535,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RecordPage(self._version, response, self._solution) + return RecordPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RecordPage: """ @@ -719,7 +641,7 @@ def get_page(self, target_url: str) -> RecordPage: :returns: Page of RecordInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RecordPage(self._version, response, self._solution) + return RecordPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RecordPage: """ @@ -731,7 +653,7 @@ async def get_page_async(self, target_url: str) -> RecordPage: :returns: Page of RecordInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RecordPage(self._version, response, self._solution) + return RecordPage(self._version, response, solution=self._solution) @property def all_time(self) -> AllTimeList: diff --git a/twilio/rest/api/v2010/account/usage/record/all_time.py b/twilio/rest/api/v2010/account/usage/record/all_time.py index 56145d98a9..3d01ff38a2 100644 --- a/twilio/rest/api/v2010/account/usage/record/all_time.py +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class AllTimeInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["AllTimeInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: :param payload: Payload response from the API """ + return AllTimeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AllTimeInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AllTimeInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AllTimeInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AllTimeInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AllTimePage(self._version, response, self._solution) + return AllTimePage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["AllTimeInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AllTimePage(self._version, response, self._solution) + return AllTimePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AllTimePage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AllTimePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AllTimePage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AllTimePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AllTimePage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> AllTimePage: :returns: Page of AllTimeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AllTimePage(self._version, response, self._solution) + return AllTimePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AllTimePage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> AllTimePage: :returns: Page of AllTimeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AllTimePage(self._version, response, self._solution) + return AllTimePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/daily.py b/twilio/rest/api/v2010/account/usage/record/daily.py index 49058b8ea2..0be683fb86 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class DailyInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["DailyInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: :param payload: Payload response from the API """ + return DailyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DailyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DailyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DailyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DailyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DailyPage(self._version, response, self._solution) + return DailyPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["DailyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DailyPage(self._version, response, self._solution) + return DailyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DailyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DailyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DailyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DailyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DailyPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> DailyPage: :returns: Page of DailyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DailyPage(self._version, response, self._solution) + return DailyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DailyPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> DailyPage: :returns: Page of DailyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DailyPage(self._version, response, self._solution) + return DailyPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/last_month.py b/twilio/rest/api/v2010/account/usage/record/last_month.py index acd98874ca..25cc8a5ce1 100644 --- a/twilio/rest/api/v2010/account/usage/record/last_month.py +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class LastMonthInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["LastMonthInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: :param payload: Payload response from the API """ + return LastMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LastMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LastMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LastMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LastMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return LastMonthPage(self._version, response, self._solution) + return LastMonthPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["LastMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return LastMonthPage(self._version, response, self._solution) + return LastMonthPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LastMonthPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LastMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LastMonthPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LastMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> LastMonthPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> LastMonthPage: :returns: Page of LastMonthInstance """ response = self._version.domain.twilio.request("GET", target_url) - return LastMonthPage(self._version, response, self._solution) + return LastMonthPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> LastMonthPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> LastMonthPage: :returns: Page of LastMonthInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return LastMonthPage(self._version, response, self._solution) + return LastMonthPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/monthly.py b/twilio/rest/api/v2010/account/usage/record/monthly.py index 3258e5f4fe..9d597023be 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class MonthlyInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["MonthlyInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: :param payload: Payload response from the API """ + return MonthlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MonthlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MonthlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MonthlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MonthlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MonthlyPage(self._version, response, self._solution) + return MonthlyPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["MonthlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MonthlyPage(self._version, response, self._solution) + return MonthlyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MonthlyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MonthlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MonthlyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MonthlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MonthlyPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> MonthlyPage: :returns: Page of MonthlyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MonthlyPage(self._version, response, self._solution) + return MonthlyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MonthlyPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> MonthlyPage: :returns: Page of MonthlyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MonthlyPage(self._version, response, self._solution) + return MonthlyPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/this_month.py b/twilio/rest/api/v2010/account/usage/record/this_month.py index cf120b91d3..b1f11399bd 100644 --- a/twilio/rest/api/v2010/account/usage/record/this_month.py +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class ThisMonthInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["ThisMonthInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: :param payload: Payload response from the API """ + return ThisMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ThisMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ThisMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ThisMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ThisMonthInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ThisMonthPage(self._version, response, self._solution) + return ThisMonthPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["ThisMonthInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ThisMonthPage(self._version, response, self._solution) + return ThisMonthPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ThisMonthPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ThisMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ThisMonthPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ThisMonthPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ThisMonthPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> ThisMonthPage: :returns: Page of ThisMonthInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ThisMonthPage(self._version, response, self._solution) + return ThisMonthPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ThisMonthPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> ThisMonthPage: :returns: Page of ThisMonthInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ThisMonthPage(self._version, response, self._solution) + return ThisMonthPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/today.py b/twilio/rest/api/v2010/account/usage/record/today.py index b2387c95b4..dfe2e1fca4 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class TodayInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["TodayInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: :param payload: Payload response from the API """ + return TodayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TodayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TodayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TodayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TodayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TodayPage(self._version, response, self._solution) + return TodayPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["TodayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TodayPage(self._version, response, self._solution) + return TodayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TodayPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TodayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TodayPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TodayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TodayPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> TodayPage: :returns: Page of TodayInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TodayPage(self._version, response, self._solution) + return TodayPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TodayPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> TodayPage: :returns: Page of TodayInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TodayPage(self._version, response, self._solution) + return TodayPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/yearly.py b/twilio/rest/api/v2010/account/usage/record/yearly.py index 490b317e72..24812d72a3 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class YearlyInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["YearlyInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: :param payload: Payload response from the API """ + return YearlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams YearlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams YearlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists YearlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists YearlyInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return YearlyPage(self._version, response, self._solution) + return YearlyPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["YearlyInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return YearlyPage(self._version, response, self._solution) + return YearlyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with YearlyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = YearlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with YearlyPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = YearlyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> YearlyPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> YearlyPage: :returns: Page of YearlyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return YearlyPage(self._version, response, self._solution) + return YearlyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> YearlyPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> YearlyPage: :returns: Page of YearlyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return YearlyPage(self._version, response, self._solution) + return YearlyPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/record/yesterday.py b/twilio/rest/api/v2010/account/usage/record/yesterday.py index da5c9dc180..32ad22f8d0 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,337 +24,11 @@ class YesterdayInstance(InstanceResource): - - class Category(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -373,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.api_version: Optional[str] = payload.get("api_version") self.as_of: Optional[str] = payload.get("as_of") - self.category: Optional["YesterdayInstance.Category"] = payload.get("category") + self.category: Optional[str] = payload.get("category") self.count: Optional[str] = payload.get("count") self.count_unit: Optional[str] = payload.get("count_unit") self.description: Optional[str] = payload.get("description") @@ -414,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: :param payload: Payload response from the API """ + return YesterdayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -449,7 +125,7 @@ def __init__(self, version: Version, account_sid: str): def stream( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -462,7 +138,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -488,7 +164,7 @@ def stream( async def stream_async( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -501,7 +177,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -525,9 +201,85 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams YesterdayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams YesterdayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -539,7 +291,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -552,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -565,7 +318,7 @@ def list( async def list_async( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -577,7 +330,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. @@ -590,6 +343,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,9 +356,83 @@ async def list_async( ) ] + def list_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists YesterdayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists YesterdayInstance and returns headers from first page + + + :param str category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -645,11 +473,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return YesterdayPage(self._version, response, self._solution) + return YesterdayPage(self._version, response, solution=self._solution) async def page_async( self, - category: Union["YesterdayInstance.Category", object] = values.unset, + category: Union[str, object] = values.unset, start_date: Union[date, object] = values.unset, end_date: Union[date, object] = values.unset, include_subaccounts: Union[bool, object] = values.unset, @@ -690,7 +518,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return YesterdayPage(self._version, response, self._solution) + return YesterdayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with YesterdayPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = YesterdayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + category: Union[str, object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with YesterdayPage, status code, and headers + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = YesterdayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> YesterdayPage: """ @@ -702,7 +624,7 @@ def get_page(self, target_url: str) -> YesterdayPage: :returns: Page of YesterdayInstance """ response = self._version.domain.twilio.request("GET", target_url) - return YesterdayPage(self._version, response, self._solution) + return YesterdayPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> YesterdayPage: """ @@ -714,7 +636,7 @@ async def get_page_async(self, target_url: str) -> YesterdayPage: :returns: Page of YesterdayInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return YesterdayPage(self._version, response, self._solution) + return YesterdayPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/api/v2010/account/usage/trigger.py b/twilio/rest/api/v2010/account/usage/trigger.py index 08ac52f605..8e975e0204 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,331 +36,6 @@ class TriggerField(object): USAGE = "usage" PRICE = "price" - class UsageCategory(object): - A2P_REGISTRATION_FEES = "a2p-registration-fees" - AGENT_CONFERENCE = "agent-conference" - AMAZON_POLLY = "amazon-polly" - ANSWERING_MACHINE_DETECTION = "answering-machine-detection" - AUTHY_AUTHENTICATIONS = "authy-authentications" - AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" - AUTHY_MONTHLY_FEES = "authy-monthly-fees" - AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" - AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" - AUTHY_SMS_OUTBOUND = "authy-sms-outbound" - CALL_PROGESS_EVENTS = "call-progess-events" - CALLERIDLOOKUPS = "calleridlookups" - CALLS = "calls" - CALLS_CLIENT = "calls-client" - CALLS_GLOBALCONFERENCE = "calls-globalconference" - CALLS_INBOUND = "calls-inbound" - CALLS_INBOUND_LOCAL = "calls-inbound-local" - CALLS_INBOUND_MOBILE = "calls-inbound-mobile" - CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" - CALLS_OUTBOUND = "calls-outbound" - CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" - CALLS_RECORDINGS = "calls-recordings" - CALLS_SIP = "calls-sip" - CALLS_SIP_INBOUND = "calls-sip-inbound" - CALLS_SIP_OUTBOUND = "calls-sip-outbound" - CALLS_TRANSFERS = "calls-transfers" - CARRIER_LOOKUPS = "carrier-lookups" - CONVERSATIONS = "conversations" - CONVERSATIONS_API_REQUESTS = "conversations-api-requests" - CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" - CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" - CONVERSATIONS_EVENTS = "conversations-events" - CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" - CONVERSATIONS_PARTICIPANTS = "conversations-participants" - CPS = "cps" - FLEX_USAGE = "flex-usage" - FRAUD_LOOKUPS = "fraud-lookups" - GROUP_ROOMS = "group-rooms" - GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" - GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" - GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" - GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" - GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" - GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" - GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" - GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" - IMP_V1_USAGE = "imp-v1-usage" - IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" - IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" - LOOKUPS = "lookups" - MARKETPLACE = "marketplace" - MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( - "marketplace-algorithmia-named-entity-recognition" - ) - MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" - MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" - MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" - MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" - MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" - MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( - "marketplace-digital-segment-business-info" - ) - MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( - "marketplace-facebook-offline-conversions" - ) - MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" - MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( - "marketplace-ibm-watson-message-insights" - ) - MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( - "marketplace-ibm-watson-message-sentiment" - ) - MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( - "marketplace-ibm-watson-recording-analysis" - ) - MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" - MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" - MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( - "marketplace-infogroup-dataaxle-bizinfo" - ) - MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( - "marketplace-keen-io-contact-center-analytics" - ) - MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" - MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( - "marketplace-marchex-sentiment-analysis-for-sms" - ) - MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( - "marketplace-marketplace-nextcaller-social-id" - ) - MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( - "marketplace-mobile-commons-opt-out-classifier" - ) - MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( - "marketplace-nexiwave-voicemail-to-text" - ) - MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( - "marketplace-nextcaller-advanced-caller-identification" - ) - MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" - MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" - MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( - "marketplace-remeeting-automatic-speech-recognition" - ) - MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( - "marketplace-tcpa-defense-solutions-blacklist-feed" - ) - MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" - MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" - MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( - "marketplace-twilio-caller-name-lookup-us" - ) - MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( - "marketplace-twilio-carrier-information-lookup" - ) - MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" - MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" - MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( - "marketplace-voicebase-transcription-custom-vocabulary" - ) - MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( - "marketplace-whitepages-pro-caller-identification" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( - "marketplace-whitepages-pro-phone-intelligence" - ) - MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( - "marketplace-whitepages-pro-phone-reputation" - ) - MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" - MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" - MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( - "marketplace-ytica-contact-center-reporting-analytics" - ) - MEDIASTORAGE = "mediastorage" - MMS = "mms" - MMS_INBOUND = "mms-inbound" - MMS_INBOUND_LONGCODE = "mms-inbound-longcode" - MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" - MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" - MMS_OUTBOUND = "mms-outbound" - MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" - MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" - MONITOR_READS = "monitor-reads" - MONITOR_STORAGE = "monitor-storage" - MONITOR_WRITES = "monitor-writes" - NOTIFY = "notify" - NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" - NOTIFY_CHANNELS = "notify-channels" - NUMBER_FORMAT_LOOKUPS = "number-format-lookups" - PCHAT = "pchat" - PCHAT_USERS = "pchat-users" - PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( - "peer-to-peer-rooms-participant-minutes" - ) - PFAX = "pfax" - PFAX_MINUTES = "pfax-minutes" - PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" - PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" - PFAX_PAGES = "pfax-pages" - PHONENUMBERS = "phonenumbers" - PHONENUMBERS_CPS = "phonenumbers-cps" - PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" - PHONENUMBERS_LOCAL = "phonenumbers-local" - PHONENUMBERS_MOBILE = "phonenumbers-mobile" - PHONENUMBERS_SETUPS = "phonenumbers-setups" - PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" - PREMIUMSUPPORT = "premiumsupport" - PROXY = "proxy" - PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" - PSTNCONNECTIVITY = "pstnconnectivity" - PV = "pv" - PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" - PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" - PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" - PV_COMPOSITION_MINUTES = "pv-composition-minutes" - PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" - PV_ROOM_PARTICIPANTS = "pv-room-participants" - PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" - PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" - PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" - PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" - PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" - PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" - PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" - PV_ROOMS = "pv-rooms" - PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" - RECORDINGS = "recordings" - RECORDINGSTORAGE = "recordingstorage" - ROOMS_GROUP_BANDWIDTH = "rooms-group-bandwidth" - ROOMS_GROUP_MINUTES = "rooms-group-minutes" - ROOMS_PEER_TO_PEER_MINUTES = "rooms-peer-to-peer-minutes" - SHORTCODES = "shortcodes" - SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" - SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" - SHORTCODES_MPS = "shortcodes-mps" - SHORTCODES_RANDOM = "shortcodes-random" - SHORTCODES_UK = "shortcodes-uk" - SHORTCODES_VANITY = "shortcodes-vanity" - SMALL_GROUP_ROOMS = "small-group-rooms" - SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" - SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" - SMS = "sms" - SMS_INBOUND = "sms-inbound" - SMS_INBOUND_LONGCODE = "sms-inbound-longcode" - SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" - SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" - SMS_MESSAGES_FEATURES = "sms-messages-features" - SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" - SMS_OUTBOUND = "sms-outbound" - SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" - SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" - SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" - SPEECH_RECOGNITION = "speech-recognition" - STUDIO_ENGAGEMENTS = "studio-engagements" - SYNC = "sync" - SYNC_ACTIONS = "sync-actions" - SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" - SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" - TASKROUTER_TASKS = "taskrouter-tasks" - TOTALPRICE = "totalprice" - TRANSCRIPTIONS = "transcriptions" - TRUNKING_CPS = "trunking-cps" - TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" - TRUNKING_ORIGINATION = "trunking-origination" - TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" - TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" - TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" - TRUNKING_RECORDINGS = "trunking-recordings" - TRUNKING_SECURE = "trunking-secure" - TRUNKING_TERMINATION = "trunking-termination" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. :ivar api_version: The API version used to create the resource. @@ -375,7 +51,7 @@ class UsageCategory(object): :ivar trigger_by: :ivar trigger_value: The value at which the trigger will fire. Must be a positive, numeric value. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. - :ivar usage_category: + :ivar usage_category: The usage category the trigger watches. Must be one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar usage_record_uri: The URI of the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource this trigger watches, relative to `https://api.twilio.com`. """ @@ -410,15 +86,14 @@ def __init__( ) self.trigger_value: Optional[str] = payload.get("trigger_value") self.uri: Optional[str] = payload.get("uri") - self.usage_category: Optional["TriggerInstance.UsageCategory"] = payload.get( - "usage_category" - ) + self.usage_category: Optional[str] = payload.get("usage_category") self.usage_record_uri: Optional[str] = payload.get("usage_record_uri") self._solution = { "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[TriggerContext] = None @property @@ -455,6 +130,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TriggerInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TriggerInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TriggerInstance": """ Fetch the TriggerInstance @@ -473,6 +166,24 @@ async def fetch_async(self) -> "TriggerInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TriggerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TriggerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, callback_method: Union[str, object] = values.unset, @@ -515,6 +226,48 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TriggerInstance with HTTP info + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TriggerInstance with HTTP info + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -546,6 +299,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TriggerInstance @@ -553,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TriggerInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -565,27 +354,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TriggerInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TriggerInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TriggerInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TriggerInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: + """ + Fetch the TriggerInstance + + :returns: The fetched TriggerInstance + """ + payload, _, _ = self._fetch() return TriggerInstance( self._version, payload, @@ -593,22 +398,46 @@ def fetch(self) -> TriggerInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TriggerInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TriggerInstance + Fetch the TriggerInstance and return response metadata - :returns: The fetched TriggerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TriggerInstance: + """ + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + payload, _, _ = await self._fetch_async() return TriggerInstance( self._version, payload, @@ -616,20 +445,33 @@ async def fetch_async(self) -> TriggerInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TriggerInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, callback_method: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> TriggerInstance: + ) -> tuple: """ - Update the TriggerInstance + Internal helper for update operation - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. - :param callback_url: The URL we should call using `callback_method` when the trigger fires. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - - :returns: The updated TriggerInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -645,10 +487,30 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + payload, _, _ = self._update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) return TriggerInstance( self._version, payload, @@ -656,20 +518,45 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, callback_method: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> TriggerInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TriggerInstance + Update the TriggerInstance and return response metadata :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. :param callback_url: The URL we should call using `callback_method` when the trigger fires. :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The updated TriggerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -685,10 +572,30 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronous coroutine to update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + payload, _, _ = await self._update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) return TriggerInstance( self._version, payload, @@ -696,6 +603,34 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TriggerInstance and return response metadata + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + instance = TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -714,6 +649,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: :param payload: Payload response from the API """ + return TriggerInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -747,29 +683,22 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, callback_url: str, trigger_value: str, - usage_category: "TriggerInstance.UsageCategory", + usage_category: str, callback_method: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - ) -> TriggerInstance: + ) -> tuple: """ - Create the TriggerInstance + Internal helper for create operation - :param callback_url: The URL we should call using `callback_method` when the trigger fires. - :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. - :param usage_category: - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param recurring: - :param trigger_by: - - :returns: The created TriggerInstance - """ + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -788,36 +717,98 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + payload, _, _ = self._create( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) return TriggerInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, callback_url: str, trigger_value: str, - usage_category: "TriggerInstance.UsageCategory", + usage_category: str, callback_method: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - ) -> TriggerInstance: + ) -> ApiResponse: """ - Asynchronously create the TriggerInstance + Create the TriggerInstance and return response metadata :param callback_url: The URL we should call using `callback_method` when the trigger fires. :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. - :param usage_category: + :param usage_category: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param recurring: :param trigger_by: - :returns: The created TriggerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + instance = TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -837,19 +828,88 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronously create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + payload, _, _ = await self._create_async( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) return TriggerInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + callback_url: str, + trigger_value: str, + usage_category: str, + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TriggerInstance and return response metadata + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: The usage category that the trigger should watch. Use one of the supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) for this value. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback_url=callback_url, + trigger_value=trigger_value, + usage_category=usage_category, + callback_method=callback_method, + friendly_name=friendly_name, + recurring=recurring, + trigger_by=trigger_by, + ) + instance = TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[TriggerInstance]: @@ -861,7 +921,7 @@ def stream( :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). - :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -885,7 +945,7 @@ async def stream_async( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[TriggerInstance]: @@ -897,7 +957,7 @@ async def stream_async( :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). - :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -917,11 +977,81 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TriggerInstance and returns headers from first page + + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TriggerInstance and returns headers from first page + + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TriggerInstance]: @@ -932,7 +1062,7 @@ def list( :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). - :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -942,6 +1072,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( recurring=recurring, @@ -956,7 +1087,7 @@ async def list_async( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TriggerInstance]: @@ -967,7 +1098,7 @@ async def list_async( :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). - :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -977,6 +1108,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -988,11 +1120,79 @@ async def list_async( ) ] + def list_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TriggerInstance and returns headers from first page + + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TriggerInstance and returns headers from first page + + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param str usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1028,13 +1228,13 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TriggerPage(self._version, response, self._solution) + return TriggerPage(self._version, response, solution=self._solution) async def page_async( self, recurring: Union["TriggerInstance.Recurring", object] = values.unset, trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, - usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + usage_category: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1070,7 +1270,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TriggerPage(self._version, response, self._solution) + return TriggerPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TriggerPage, status code, and headers + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TriggerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TriggerPage, status code, and headers + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TriggerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TriggerPage: """ @@ -1082,7 +1370,7 @@ def get_page(self, target_url: str) -> TriggerPage: :returns: Page of TriggerInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TriggerPage(self._version, response, self._solution) + return TriggerPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TriggerPage: """ @@ -1094,7 +1382,7 @@ async def get_page_async(self, target_url: str) -> TriggerPage: :returns: Page of TriggerInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TriggerPage(self._version, response, self._solution) + return TriggerPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TriggerContext: """ diff --git a/twilio/rest/api/v2010/account/validation_request.py b/twilio/rest/api/v2010/account/validation_request.py index d92f840e68..9594e19cc1 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,7 +73,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, friendly_name: Union[str, object] = values.unset, @@ -80,18 +81,12 @@ def create( extension: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> ValidationRequestInstance: + ) -> tuple: """ - Create the ValidationRequestInstance - - :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. - :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. - :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. - :param extension: The digits to dial after connecting the verification call. - :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + Internal helper for create operation - :returns: The created ValidationRequestInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -110,15 +105,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) return ValidationRequestInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, friendly_name: Union[str, object] = values.unset, @@ -126,9 +150,9 @@ async def create_async( extension: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> ValidationRequestInstance: + ) -> ApiResponse: """ - Asynchronously create the ValidationRequestInstance + Create the ValidationRequestInstance and return response metadata :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. @@ -137,7 +161,35 @@ async def create_async( :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. - :returns: The created ValidationRequestInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -156,14 +208,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Asynchronously create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) return ValidationRequestInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ValidationRequestInstance and return response metadata + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/assistants/__init__.py b/twilio/rest/assistants/__init__.py deleted file mode 100644 index 60c812014d..0000000000 --- a/twilio/rest/assistants/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -from warnings import warn - -from twilio.rest.assistants import AssistantsBase -from twilio.rest.assistants.v1.assistant import AssistantList -from twilio.rest.assistants.v1.knowledge import KnowledgeList -from twilio.rest.assistants.v1.policy import PolicyList -from twilio.rest.assistants.v1.session import SessionList -from twilio.rest.assistants.v1.tool import ToolList - - -class Assistants(AssistantsBase): - - @property - def assistants(self) -> AssistantList: - warn( - "assistants is deprecated. Use v1.assistants instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.assistants - - @property - def knowledge(self) -> KnowledgeList: - warn( - "knowledge is deprecated. Use v1.knowledge instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.knowledge - - @property - def policies(self) -> PolicyList: - warn( - "policies is deprecated. Use v1.policies instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.policies - - @property - def sessions(self) -> SessionList: - warn( - "sessions is deprecated. Use v1.sessions instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.sessions - - @property - def tools(self) -> ToolList: - warn( - "tools is deprecated. Use v1.tools instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.tools diff --git a/twilio/rest/assistants/v1/__init__.py b/twilio/rest/assistants/v1/__init__.py deleted file mode 100644 index 546ad14554..0000000000 --- a/twilio/rest/assistants/v1/__init__.py +++ /dev/null @@ -1,75 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Optional -from twilio.base.version import Version -from twilio.base.domain import Domain -from twilio.rest.assistants.v1.assistant import AssistantList -from twilio.rest.assistants.v1.knowledge import KnowledgeList -from twilio.rest.assistants.v1.policy import PolicyList -from twilio.rest.assistants.v1.session import SessionList -from twilio.rest.assistants.v1.tool import ToolList - - -class V1(Version): - - def __init__(self, domain: Domain): - """ - Initialize the V1 version of Assistants - - :param domain: The Twilio.assistants domain - """ - super().__init__(domain, "v1") - self._assistants: Optional[AssistantList] = None - self._knowledge: Optional[KnowledgeList] = None - self._policies: Optional[PolicyList] = None - self._sessions: Optional[SessionList] = None - self._tools: Optional[ToolList] = None - - @property - def assistants(self) -> AssistantList: - if self._assistants is None: - self._assistants = AssistantList(self) - return self._assistants - - @property - def knowledge(self) -> KnowledgeList: - if self._knowledge is None: - self._knowledge = KnowledgeList(self) - return self._knowledge - - @property - def policies(self) -> PolicyList: - if self._policies is None: - self._policies = PolicyList(self) - return self._policies - - @property - def sessions(self) -> SessionList: - if self._sessions is None: - self._sessions = SessionList(self) - return self._sessions - - @property - def tools(self) -> ToolList: - if self._tools is None: - self._tools = ToolList(self) - return self._tools - - def __repr__(self) -> str: - """ - Provide a friendly representation - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/assistant/__init__.py b/twilio/rest/assistants/v1/assistant/__init__.py deleted file mode 100644 index 8ab22a5dcf..0000000000 --- a/twilio/rest/assistants/v1/assistant/__init__.py +++ /dev/null @@ -1,1036 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.assistants.v1.assistant.assistants_knowledge import ( - AssistantsKnowledgeList, -) -from twilio.rest.assistants.v1.assistant.assistants_tool import AssistantsToolList -from twilio.rest.assistants.v1.assistant.feedback import FeedbackList -from twilio.rest.assistants.v1.assistant.message import MessageList - - -class AssistantInstance(InstanceResource): - - class AssistantsV1ServiceCreateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - class AssistantsV1ServiceCustomerAi(object): - """ - :ivar perception_engine_enabled: True if the perception engine is enabled. - :ivar personalization_engine_enabled: True if the personalization engine is enabled. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.perception_engine_enabled: Optional[bool] = payload.get( - "perception_engine_enabled" - ) - self.personalization_engine_enabled: Optional[bool] = payload.get( - "personalization_engine_enabled" - ) - - def to_dict(self): - return { - "perception_engine_enabled": self.perception_engine_enabled, - "personalization_engine_enabled": self.personalization_engine_enabled, - } - - class AssistantsV1ServiceSegmentCredential(object): - """ - :ivar profile_api_key: The profile API key. - :ivar space_id: The space ID. - :ivar write_key: The write key. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.profile_api_key: Optional[str] = payload.get("profile_api_key") - self.space_id: Optional[str] = payload.get("space_id") - self.write_key: Optional[str] = payload.get("write_key") - - def to_dict(self): - return { - "profile_api_key": self.profile_api_key, - "space_id": self.space_id, - "write_key": self.write_key, - } - - class AssistantsV1ServiceUpdateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. - :ivar customer_ai: The Personalization and Perception Engine settings. - :ivar id: The Assistant ID. - :ivar model: The default model used by the assistant. - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar url: The url of the assistant resource. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar date_created: The date and time in GMT when the Assistant was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Assistant was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar knowledge: The list of knowledge sources associated with the assistant. - :ivar tools: The list of tools associated with the assistant. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], id: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.customer_ai: Optional[Dict[str, object]] = payload.get("customer_ai") - self.id: Optional[str] = payload.get("id") - self.model: Optional[str] = payload.get("model") - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.url: Optional[str] = payload.get("url") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.knowledge: Optional[List[str]] = payload.get("knowledge") - self.tools: Optional[List[str]] = payload.get("tools") - - self._solution = { - "id": id or self.id, - } - self._context: Optional[AssistantContext] = None - - @property - def _proxy(self) -> "AssistantContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AssistantContext for this AssistantInstance - """ - if self._context is None: - self._context = AssistantContext( - self._version, - id=self._solution["id"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "AssistantInstance": - """ - Fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AssistantInstance": - """ - Asynchronous coroutine to fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - assistants_v1_service_update_assistant_request: Union[ - AssistantsV1ServiceUpdateAssistantRequest, object - ] = values.unset, - ) -> "AssistantInstance": - """ - Update the AssistantInstance - - :param assistants_v1_service_update_assistant_request: - - :returns: The updated AssistantInstance - """ - return self._proxy.update( - assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, - ) - - async def update_async( - self, - assistants_v1_service_update_assistant_request: Union[ - AssistantsV1ServiceUpdateAssistantRequest, object - ] = values.unset, - ) -> "AssistantInstance": - """ - Asynchronous coroutine to update the AssistantInstance - - :param assistants_v1_service_update_assistant_request: - - :returns: The updated AssistantInstance - """ - return await self._proxy.update_async( - assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, - ) - - @property - def assistants_knowledge(self) -> AssistantsKnowledgeList: - """ - Access the assistants_knowledge - """ - return self._proxy.assistants_knowledge - - @property - def assistants_tools(self) -> AssistantsToolList: - """ - Access the assistants_tools - """ - return self._proxy.assistants_tools - - @property - def feedbacks(self) -> FeedbackList: - """ - Access the feedbacks - """ - return self._proxy.feedbacks - - @property - def messages(self) -> MessageList: - """ - Access the messages - """ - return self._proxy.messages - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantContext(InstanceContext): - - class AssistantsV1ServiceCreateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - class AssistantsV1ServiceCustomerAi(object): - """ - :ivar perception_engine_enabled: True if the perception engine is enabled. - :ivar personalization_engine_enabled: True if the personalization engine is enabled. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.perception_engine_enabled: Optional[bool] = payload.get( - "perception_engine_enabled" - ) - self.personalization_engine_enabled: Optional[bool] = payload.get( - "personalization_engine_enabled" - ) - - def to_dict(self): - return { - "perception_engine_enabled": self.perception_engine_enabled, - "personalization_engine_enabled": self.personalization_engine_enabled, - } - - class AssistantsV1ServiceSegmentCredential(object): - """ - :ivar profile_api_key: The profile API key. - :ivar space_id: The space ID. - :ivar write_key: The write key. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.profile_api_key: Optional[str] = payload.get("profile_api_key") - self.space_id: Optional[str] = payload.get("space_id") - self.write_key: Optional[str] = payload.get("write_key") - - def to_dict(self): - return { - "profile_api_key": self.profile_api_key, - "space_id": self.space_id, - "write_key": self.write_key, - } - - class AssistantsV1ServiceUpdateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - def __init__(self, version: Version, id: str): - """ - Initialize the AssistantContext - - :param version: Version that contains the resource - :param id: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "id": id, - } - self._uri = "/Assistants/{id}".format(**self._solution) - - self._assistants_knowledge: Optional[AssistantsKnowledgeList] = None - self._assistants_tools: Optional[AssistantsToolList] = None - self._feedbacks: Optional[FeedbackList] = None - self._messages: Optional[MessageList] = None - - def delete(self) -> bool: - """ - Deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> AssistantInstance: - """ - Fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return AssistantInstance( - self._version, - payload, - id=self._solution["id"], - ) - - async def fetch_async(self) -> AssistantInstance: - """ - Asynchronous coroutine to fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return AssistantInstance( - self._version, - payload, - id=self._solution["id"], - ) - - def update( - self, - assistants_v1_service_update_assistant_request: Union[ - AssistantsV1ServiceUpdateAssistantRequest, object - ] = values.unset, - ) -> AssistantInstance: - """ - Update the AssistantInstance - - :param assistants_v1_service_update_assistant_request: - - :returns: The updated AssistantInstance - """ - data = assistants_v1_service_update_assistant_request.to_dict() - - headers = values.of({}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="PUT", uri=self._uri, data=data, headers=headers - ) - - return AssistantInstance(self._version, payload, id=self._solution["id"]) - - async def update_async( - self, - assistants_v1_service_update_assistant_request: Union[ - AssistantsV1ServiceUpdateAssistantRequest, object - ] = values.unset, - ) -> AssistantInstance: - """ - Asynchronous coroutine to update the AssistantInstance - - :param assistants_v1_service_update_assistant_request: - - :returns: The updated AssistantInstance - """ - data = assistants_v1_service_update_assistant_request.to_dict() - - headers = values.of({}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="PUT", uri=self._uri, data=data, headers=headers - ) - - return AssistantInstance(self._version, payload, id=self._solution["id"]) - - @property - def assistants_knowledge(self) -> AssistantsKnowledgeList: - """ - Access the assistants_knowledge - """ - if self._assistants_knowledge is None: - self._assistants_knowledge = AssistantsKnowledgeList( - self._version, - self._solution["id"], - ) - return self._assistants_knowledge - - @property - def assistants_tools(self) -> AssistantsToolList: - """ - Access the assistants_tools - """ - if self._assistants_tools is None: - self._assistants_tools = AssistantsToolList( - self._version, - self._solution["id"], - ) - return self._assistants_tools - - @property - def feedbacks(self) -> FeedbackList: - """ - Access the feedbacks - """ - if self._feedbacks is None: - self._feedbacks = FeedbackList( - self._version, - self._solution["id"], - ) - return self._feedbacks - - @property - def messages(self) -> MessageList: - """ - Access the messages - """ - if self._messages is None: - self._messages = MessageList( - self._version, - self._solution["id"], - ) - return self._messages - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AssistantInstance: - """ - Build an instance of AssistantInstance - - :param payload: Payload response from the API - """ - return AssistantInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class AssistantList(ListResource): - - class AssistantsV1ServiceCreateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - class AssistantsV1ServiceCustomerAi(object): - """ - :ivar perception_engine_enabled: True if the perception engine is enabled. - :ivar personalization_engine_enabled: True if the personalization engine is enabled. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.perception_engine_enabled: Optional[bool] = payload.get( - "perception_engine_enabled" - ) - self.personalization_engine_enabled: Optional[bool] = payload.get( - "personalization_engine_enabled" - ) - - def to_dict(self): - return { - "perception_engine_enabled": self.perception_engine_enabled, - "personalization_engine_enabled": self.personalization_engine_enabled, - } - - class AssistantsV1ServiceSegmentCredential(object): - """ - :ivar profile_api_key: The profile API key. - :ivar space_id: The space ID. - :ivar write_key: The write key. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.profile_api_key: Optional[str] = payload.get("profile_api_key") - self.space_id: Optional[str] = payload.get("space_id") - self.write_key: Optional[str] = payload.get("write_key") - - def to_dict(self): - return { - "profile_api_key": self.profile_api_key, - "space_id": self.space_id, - "write_key": self.write_key, - } - - class AssistantsV1ServiceUpdateAssistantRequest(object): - """ - :ivar customer_ai: - :ivar name: The name of the assistant. - :ivar owner: The owner/company of the assistant. - :ivar personality_prompt: The personality prompt to be used for assistant. - :ivar segment_credential: - """ - - def __init__(self, payload: Dict[str, Any]): - - self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( - payload.get("customer_ai") - ) - self.name: Optional[str] = payload.get("name") - self.owner: Optional[str] = payload.get("owner") - self.personality_prompt: Optional[str] = payload.get("personality_prompt") - self.segment_credential: Optional[ - AssistantList.AssistantsV1ServiceSegmentCredential - ] = payload.get("segment_credential") - - def to_dict(self): - return { - "customer_ai": ( - self.customer_ai.to_dict() if self.customer_ai is not None else None - ), - "name": self.name, - "owner": self.owner, - "personality_prompt": self.personality_prompt, - "segment_credential": ( - self.segment_credential.to_dict() - if self.segment_credential is not None - else None - ), - } - - def __init__(self, version: Version): - """ - Initialize the AssistantList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Assistants" - - def create( - self, - assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, - ) -> AssistantInstance: - """ - Create the AssistantInstance - - :param assistants_v1_service_create_assistant_request: - - :returns: The created AssistantInstance - """ - data = assistants_v1_service_create_assistant_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AssistantInstance(self._version, payload) - - async def create_async( - self, - assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, - ) -> AssistantInstance: - """ - Asynchronously create the AssistantInstance - - :param assistants_v1_service_create_assistant_request: - - :returns: The created AssistantInstance - """ - data = assistants_v1_service_create_assistant_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AssistantInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AssistantInstance]: - """ - Streams AssistantInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AssistantInstance]: - """ - Asynchronously streams AssistantInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantInstance]: - """ - Lists AssistantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantInstance]: - """ - Asynchronously lists AssistantInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantPage: - """ - Retrieve a single page of AssistantInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantPage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantPage: - """ - Asynchronously retrieve a single page of AssistantInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantPage(self._version, response) - - def get_page(self, target_url: str) -> AssistantPage: - """ - Retrieve a specific page of AssistantInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AssistantPage(self._version, response) - - async def get_page_async(self, target_url: str) -> AssistantPage: - """ - Asynchronously retrieve a specific page of AssistantInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AssistantPage(self._version, response) - - def get(self, id: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param id: - """ - return AssistantContext(self._version, id=id) - - def __call__(self, id: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param id: - """ - return AssistantContext(self._version, id=id) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/assistant/assistants_knowledge.py b/twilio/rest/assistants/v1/assistant/assistants_knowledge.py deleted file mode 100644 index 681d71789b..0000000000 --- a/twilio/rest/assistants/v1/assistant/assistants_knowledge.py +++ /dev/null @@ -1,520 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class AssistantsKnowledgeInstance(InstanceResource): - """ - :ivar description: The type of knowledge source. - :ivar id: The description of knowledge. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. - :ivar knowledge_source_details: The details of the knowledge source based on the type. - :ivar name: The name of the knowledge source. - :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') - :ivar type: The type of knowledge source ('Web', 'Database', 'Text', 'File') - :ivar url: The url of the knowledge resource. - :ivar embedding_model: The embedding model to be used for the knowledge source. - :ivar date_created: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_id: str, - id: Optional[str] = None, - ): - super().__init__(version) - - self.description: Optional[str] = payload.get("description") - self.id: Optional[str] = payload.get("id") - self.account_sid: Optional[str] = payload.get("account_sid") - self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( - "knowledge_source_details" - ) - self.name: Optional[str] = payload.get("name") - self.status: Optional[str] = payload.get("status") - self.type: Optional[str] = payload.get("type") - self.url: Optional[str] = payload.get("url") - self.embedding_model: Optional[str] = payload.get("embedding_model") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - self._solution = { - "assistant_id": assistant_id, - "id": id or self.id, - } - self._context: Optional[AssistantsKnowledgeContext] = None - - @property - def _proxy(self) -> "AssistantsKnowledgeContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AssistantsKnowledgeContext for this AssistantsKnowledgeInstance - """ - if self._context is None: - self._context = AssistantsKnowledgeContext( - self._version, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - return self._context - - def create(self) -> "AssistantsKnowledgeInstance": - """ - Create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - return self._proxy.create() - - async def create_async(self) -> "AssistantsKnowledgeInstance": - """ - Asynchronous coroutine to create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - return await self._proxy.create_async() - - def delete(self) -> bool: - """ - Deletes the AssistantsKnowledgeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantsKnowledgeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantsKnowledgeContext(InstanceContext): - - def __init__(self, version: Version, assistant_id: str, id: str): - """ - Initialize the AssistantsKnowledgeContext - - :param version: Version that contains the resource - :param assistant_id: The assistant ID. - :param id: The knowledge ID. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_id": assistant_id, - "id": id, - } - self._uri = "/Assistants/{assistant_id}/Knowledge/{id}".format(**self._solution) - - def create(self) -> AssistantsKnowledgeInstance: - """ - Create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - data = values.of({}) - - payload = self._version.create(method="POST", uri=self._uri, data=data) - - return AssistantsKnowledgeInstance( - self._version, - payload, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - - async def create_async(self) -> AssistantsKnowledgeInstance: - """ - Asynchronous coroutine to create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) - - return AssistantsKnowledgeInstance( - self._version, - payload, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - - def delete(self) -> bool: - """ - Deletes the AssistantsKnowledgeInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantsKnowledgeInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantsKnowledgePage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AssistantsKnowledgeInstance: - """ - Build an instance of AssistantsKnowledgeInstance - - :param payload: Payload response from the API - """ - return AssistantsKnowledgeInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class AssistantsKnowledgeList(ListResource): - - def __init__(self, version: Version, assistant_id: str): - """ - Initialize the AssistantsKnowledgeList - - :param version: Version that contains the resource - :param assistant_id: The assistant ID. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_id": assistant_id, - } - self._uri = "/Assistants/{assistant_id}/Knowledge".format(**self._solution) - - def create(self) -> AssistantsKnowledgeInstance: - """ - Create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create(method="POST", uri=self._uri, headers=headers) - - return AssistantsKnowledgeInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - async def create_async(self) -> AssistantsKnowledgeInstance: - """ - Asynchronously create the AssistantsKnowledgeInstance - - - :returns: The created AssistantsKnowledgeInstance - """ - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, headers=headers - ) - - return AssistantsKnowledgeInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AssistantsKnowledgeInstance]: - """ - Streams AssistantsKnowledgeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AssistantsKnowledgeInstance]: - """ - Asynchronously streams AssistantsKnowledgeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantsKnowledgeInstance]: - """ - Lists AssistantsKnowledgeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantsKnowledgeInstance]: - """ - Asynchronously lists AssistantsKnowledgeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantsKnowledgePage: - """ - Retrieve a single page of AssistantsKnowledgeInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantsKnowledgeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantsKnowledgePage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantsKnowledgePage: - """ - Asynchronously retrieve a single page of AssistantsKnowledgeInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantsKnowledgeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantsKnowledgePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> AssistantsKnowledgePage: - """ - Retrieve a specific page of AssistantsKnowledgeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantsKnowledgeInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AssistantsKnowledgePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> AssistantsKnowledgePage: - """ - Asynchronously retrieve a specific page of AssistantsKnowledgeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantsKnowledgeInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AssistantsKnowledgePage(self._version, response, self._solution) - - def get(self, id: str) -> AssistantsKnowledgeContext: - """ - Constructs a AssistantsKnowledgeContext - - :param id: The knowledge ID. - """ - return AssistantsKnowledgeContext( - self._version, assistant_id=self._solution["assistant_id"], id=id - ) - - def __call__(self, id: str) -> AssistantsKnowledgeContext: - """ - Constructs a AssistantsKnowledgeContext - - :param id: The knowledge ID. - """ - return AssistantsKnowledgeContext( - self._version, assistant_id=self._solution["assistant_id"], id=id - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/assistant/assistants_tool.py b/twilio/rest/assistants/v1/assistant/assistants_tool.py deleted file mode 100644 index ed02410d3c..0000000000 --- a/twilio/rest/assistants/v1/assistant/assistants_tool.py +++ /dev/null @@ -1,518 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class AssistantsToolInstance(InstanceResource): - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar id: The tool ID. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar requires_auth: The authentication requirement for the tool. - :ivar type: The type of the tool. ('WEBHOOK') - :ivar url: The url of the tool resource. - :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_id: str, - id: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.id: Optional[str] = payload.get("id") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.requires_auth: Optional[bool] = payload.get("requires_auth") - self.type: Optional[str] = payload.get("type") - self.url: Optional[str] = payload.get("url") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - self._solution = { - "assistant_id": assistant_id, - "id": id or self.id, - } - self._context: Optional[AssistantsToolContext] = None - - @property - def _proxy(self) -> "AssistantsToolContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AssistantsToolContext for this AssistantsToolInstance - """ - if self._context is None: - self._context = AssistantsToolContext( - self._version, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - return self._context - - def create(self) -> "AssistantsToolInstance": - """ - Create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - return self._proxy.create() - - async def create_async(self) -> "AssistantsToolInstance": - """ - Asynchronous coroutine to create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - return await self._proxy.create_async() - - def delete(self) -> bool: - """ - Deletes the AssistantsToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantsToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantsToolContext(InstanceContext): - - def __init__(self, version: Version, assistant_id: str, id: str): - """ - Initialize the AssistantsToolContext - - :param version: Version that contains the resource - :param assistant_id: The assistant ID. - :param id: The tool ID. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_id": assistant_id, - "id": id, - } - self._uri = "/Assistants/{assistant_id}/Tools/{id}".format(**self._solution) - - def create(self) -> AssistantsToolInstance: - """ - Create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - data = values.of({}) - - payload = self._version.create(method="POST", uri=self._uri, data=data) - - return AssistantsToolInstance( - self._version, - payload, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - - async def create_async(self) -> AssistantsToolInstance: - """ - Asynchronous coroutine to create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) - - return AssistantsToolInstance( - self._version, - payload, - assistant_id=self._solution["assistant_id"], - id=self._solution["id"], - ) - - def delete(self) -> bool: - """ - Deletes the AssistantsToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantsToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class AssistantsToolPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AssistantsToolInstance: - """ - Build an instance of AssistantsToolInstance - - :param payload: Payload response from the API - """ - return AssistantsToolInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class AssistantsToolList(ListResource): - - def __init__(self, version: Version, assistant_id: str): - """ - Initialize the AssistantsToolList - - :param version: Version that contains the resource - :param assistant_id: The assistant ID. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_id": assistant_id, - } - self._uri = "/Assistants/{assistant_id}/Tools".format(**self._solution) - - def create(self) -> AssistantsToolInstance: - """ - Create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create(method="POST", uri=self._uri, headers=headers) - - return AssistantsToolInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - async def create_async(self) -> AssistantsToolInstance: - """ - Asynchronously create the AssistantsToolInstance - - - :returns: The created AssistantsToolInstance - """ - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, headers=headers - ) - - return AssistantsToolInstance( - self._version, payload, assistant_id=self._solution["assistant_id"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AssistantsToolInstance]: - """ - Streams AssistantsToolInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AssistantsToolInstance]: - """ - Asynchronously streams AssistantsToolInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantsToolInstance]: - """ - Lists AssistantsToolInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AssistantsToolInstance]: - """ - Asynchronously lists AssistantsToolInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantsToolPage: - """ - Retrieve a single page of AssistantsToolInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantsToolInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantsToolPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AssistantsToolPage: - """ - Asynchronously retrieve a single page of AssistantsToolInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AssistantsToolInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AssistantsToolPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> AssistantsToolPage: - """ - Retrieve a specific page of AssistantsToolInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantsToolInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AssistantsToolPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> AssistantsToolPage: - """ - Asynchronously retrieve a specific page of AssistantsToolInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AssistantsToolInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AssistantsToolPage(self._version, response, self._solution) - - def get(self, id: str) -> AssistantsToolContext: - """ - Constructs a AssistantsToolContext - - :param id: The tool ID. - """ - return AssistantsToolContext( - self._version, assistant_id=self._solution["assistant_id"], id=id - ) - - def __call__(self, id: str) -> AssistantsToolContext: - """ - Constructs a AssistantsToolContext - - :param id: The tool ID. - """ - return AssistantsToolContext( - self._version, assistant_id=self._solution["assistant_id"], id=id - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/assistant/feedback.py b/twilio/rest/assistants/v1/assistant/feedback.py deleted file mode 100644 index 77c6d405f4..0000000000 --- a/twilio/rest/assistants/v1/assistant/feedback.py +++ /dev/null @@ -1,404 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class FeedbackInstance(InstanceResource): - - class AssistantsV1ServiceCreateFeedbackRequest(object): - """ - :ivar message_id: The message ID. - :ivar score: The score to be given(0-1). - :ivar session_id: The Session ID. - :ivar text: The text to be given as feedback. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.message_id: Optional[str] = payload.get("message_id") - self.score: Optional[float] = payload.get("score") - self.session_id: Optional[str] = payload.get("session_id") - self.text: Optional[str] = payload.get("text") - - def to_dict(self): - return { - "message_id": self.message_id, - "score": self.score, - "session_id": self.session_id, - "text": self.text, - } - - """ - :ivar assistant_id: The Assistant ID. - :ivar id: The Feedback ID. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Feedback. - :ivar user_sid: The SID of the User created the Feedback. - :ivar message_id: The Message ID. - :ivar score: The Score to provide as Feedback (0-1) - :ivar session_id: The Session ID. - :ivar text: The text to be given as feedback. - :ivar date_created: The date and time in GMT when the Feedback was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Feedback was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__(self, version: Version, payload: Dict[str, Any], id: str): - super().__init__(version) - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.id: Optional[str] = payload.get("id") - self.account_sid: Optional[str] = payload.get("account_sid") - self.user_sid: Optional[str] = payload.get("user_sid") - self.message_id: Optional[str] = payload.get("message_id") - self.score: Optional[float] = payload.get("score") - self.session_id: Optional[str] = payload.get("session_id") - self.text: Optional[str] = payload.get("text") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - self._solution = { - "id": id, - } - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class FeedbackPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> FeedbackInstance: - """ - Build an instance of FeedbackInstance - - :param payload: Payload response from the API - """ - return FeedbackInstance(self._version, payload, id=self._solution["id"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FeedbackList(ListResource): - - class AssistantsV1ServiceCreateFeedbackRequest(object): - """ - :ivar message_id: The message ID. - :ivar score: The score to be given(0-1). - :ivar session_id: The Session ID. - :ivar text: The text to be given as feedback. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.message_id: Optional[str] = payload.get("message_id") - self.score: Optional[float] = payload.get("score") - self.session_id: Optional[str] = payload.get("session_id") - self.text: Optional[str] = payload.get("text") - - def to_dict(self): - return { - "message_id": self.message_id, - "score": self.score, - "session_id": self.session_id, - "text": self.text, - } - - def __init__(self, version: Version, id: str): - """ - Initialize the FeedbackList - - :param version: Version that contains the resource - :param id: The assistant ID. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "id": id, - } - self._uri = "/Assistants/{id}/Feedbacks".format(**self._solution) - - def create( - self, - assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, - ) -> FeedbackInstance: - """ - Create the FeedbackInstance - - :param assistants_v1_service_create_feedback_request: - - :returns: The created FeedbackInstance - """ - data = assistants_v1_service_create_feedback_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return FeedbackInstance(self._version, payload, id=self._solution["id"]) - - async def create_async( - self, - assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, - ) -> FeedbackInstance: - """ - Asynchronously create the FeedbackInstance - - :param assistants_v1_service_create_feedback_request: - - :returns: The created FeedbackInstance - """ - data = assistants_v1_service_create_feedback_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return FeedbackInstance(self._version, payload, id=self._solution["id"]) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FeedbackInstance]: - """ - Streams FeedbackInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[FeedbackInstance]: - """ - Asynchronously streams FeedbackInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FeedbackInstance]: - """ - Lists FeedbackInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FeedbackInstance]: - """ - Asynchronously lists FeedbackInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> FeedbackPage: - """ - Retrieve a single page of FeedbackInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of FeedbackInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return FeedbackPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> FeedbackPage: - """ - Asynchronously retrieve a single page of FeedbackInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of FeedbackInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return FeedbackPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FeedbackPage: - """ - Retrieve a specific page of FeedbackInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FeedbackInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FeedbackPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FeedbackPage: - """ - Asynchronously retrieve a specific page of FeedbackInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FeedbackInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FeedbackPage(self._version, response, self._solution) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/assistant/message.py b/twilio/rest/assistants/v1/assistant/message.py deleted file mode 100644 index 11d73776b7..0000000000 --- a/twilio/rest/assistants/v1/assistant/message.py +++ /dev/null @@ -1,186 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, Optional -from twilio.base import values - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version - - -class MessageInstance(InstanceResource): - - class AssistantsV1ServiceAssistantSendMessageRequest(object): - """ - :ivar identity: The unique identity of user for the session. - :ivar session_id: The unique name for the session. - :ivar body: The query to ask the assistant. - :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. - :ivar mode: one of the modes 'chat', 'email' or 'voice' - """ - - def __init__(self, payload: Dict[str, Any]): - - self.identity: Optional[str] = payload.get("identity") - self.session_id: Optional[str] = payload.get("session_id") - self.body: Optional[str] = payload.get("body") - self.webhook: Optional[str] = payload.get("webhook") - self.mode: Optional[str] = payload.get("mode") - - def to_dict(self): - return { - "identity": self.identity, - "session_id": self.session_id, - "body": self.body, - "webhook": self.webhook, - "mode": self.mode, - } - - """ - :ivar status: success or failure based on whether the request successfully generated a response. - :ivar flagged: If successful, this property will denote whether the response was flagged or not. - :ivar aborted: This property will denote whether the request was aborted or not. - :ivar session_id: The unique name for the session. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that sent the Message. - :ivar body: If successful, the body of the generated response - :ivar error: The error message if generation was not successful - """ - - def __init__(self, version: Version, payload: Dict[str, Any], id: str): - super().__init__(version) - - self.status: Optional[str] = payload.get("status") - self.flagged: Optional[bool] = payload.get("flagged") - self.aborted: Optional[bool] = payload.get("aborted") - self.session_id: Optional[str] = payload.get("session_id") - self.account_sid: Optional[str] = payload.get("account_sid") - self.body: Optional[str] = payload.get("body") - self.error: Optional[str] = payload.get("error") - - self._solution = { - "id": id, - } - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class MessageList(ListResource): - - class AssistantsV1ServiceAssistantSendMessageRequest(object): - """ - :ivar identity: The unique identity of user for the session. - :ivar session_id: The unique name for the session. - :ivar body: The query to ask the assistant. - :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. - :ivar mode: one of the modes 'chat', 'email' or 'voice' - """ - - def __init__(self, payload: Dict[str, Any]): - - self.identity: Optional[str] = payload.get("identity") - self.session_id: Optional[str] = payload.get("session_id") - self.body: Optional[str] = payload.get("body") - self.webhook: Optional[str] = payload.get("webhook") - self.mode: Optional[str] = payload.get("mode") - - def to_dict(self): - return { - "identity": self.identity, - "session_id": self.session_id, - "body": self.body, - "webhook": self.webhook, - "mode": self.mode, - } - - def __init__(self, version: Version, id: str): - """ - Initialize the MessageList - - :param version: Version that contains the resource - :param id: the Assistant ID. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "id": id, - } - self._uri = "/Assistants/{id}/Messages".format(**self._solution) - - def create( - self, - assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, - ) -> MessageInstance: - """ - Create the MessageInstance - - :param assistants_v1_service_assistant_send_message_request: - - :returns: The created MessageInstance - """ - data = assistants_v1_service_assistant_send_message_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return MessageInstance(self._version, payload, id=self._solution["id"]) - - async def create_async( - self, - assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, - ) -> MessageInstance: - """ - Asynchronously create the MessageInstance - - :param assistants_v1_service_assistant_send_message_request: - - :returns: The created MessageInstance - """ - data = assistants_v1_service_assistant_send_message_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return MessageInstance(self._version, payload, id=self._solution["id"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/policy.py b/twilio/rest/assistants/v1/policy.py deleted file mode 100644 index 63854fb82b..0000000000 --- a/twilio/rest/assistants/v1/policy.py +++ /dev/null @@ -1,332 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class PolicyInstance(InstanceResource): - """ - :ivar id: The Policy ID. - :ivar name: The name of the policy. - :ivar description: The description of the policy. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Policy resource. - :ivar user_sid: The SID of the User that created the Policy resource. - :ivar type: The type of the policy. - :ivar policy_details: The details of the policy based on the type. - :ivar date_created: The date and time in GMT when the Policy was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Policy was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.id: Optional[str] = payload.get("id") - self.name: Optional[str] = payload.get("name") - self.description: Optional[str] = payload.get("description") - self.account_sid: Optional[str] = payload.get("account_sid") - self.user_sid: Optional[str] = payload.get("user_sid") - self.type: Optional[str] = payload.get("type") - self.policy_details: Optional[Dict[str, object]] = payload.get("policy_details") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class PolicyPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> PolicyInstance: - """ - Build an instance of PolicyInstance - - :param payload: Payload response from the API - """ - return PolicyInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class PolicyList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the PolicyList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Policies" - - def stream( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[PolicyInstance]: - """ - Streams PolicyInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param str tool_id: The tool ID. - :param str knowledge_id: The knowledge ID. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page( - tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[PolicyInstance]: - """ - Asynchronously streams PolicyInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param str tool_id: The tool ID. - :param str knowledge_id: The knowledge ID. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[PolicyInstance]: - """ - Lists PolicyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str tool_id: The tool ID. - :param str knowledge_id: The knowledge ID. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - tool_id=tool_id, - knowledge_id=knowledge_id, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[PolicyInstance]: - """ - Asynchronously lists PolicyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str tool_id: The tool ID. - :param str knowledge_id: The knowledge ID. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - tool_id=tool_id, - knowledge_id=knowledge_id, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> PolicyPage: - """ - Retrieve a single page of PolicyInstance records from the API. - Request is executed immediately - - :param tool_id: The tool ID. - :param knowledge_id: The knowledge ID. - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of PolicyInstance - """ - data = values.of( - { - "ToolId": tool_id, - "KnowledgeId": knowledge_id, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return PolicyPage(self._version, response) - - async def page_async( - self, - tool_id: Union[str, object] = values.unset, - knowledge_id: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> PolicyPage: - """ - Asynchronously retrieve a single page of PolicyInstance records from the API. - Request is executed immediately - - :param tool_id: The tool ID. - :param knowledge_id: The knowledge ID. - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of PolicyInstance - """ - data = values.of( - { - "ToolId": tool_id, - "KnowledgeId": knowledge_id, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return PolicyPage(self._version, response) - - def get_page(self, target_url: str) -> PolicyPage: - """ - Retrieve a specific page of PolicyInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of PolicyInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return PolicyPage(self._version, response) - - async def get_page_async(self, target_url: str) -> PolicyPage: - """ - Asynchronously retrieve a specific page of PolicyInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of PolicyInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return PolicyPage(self._version, response) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/session/__init__.py b/twilio/rest/assistants/v1/session/__init__.py deleted file mode 100644 index 3f0054ea55..0000000000 --- a/twilio/rest/assistants/v1/session/__init__.py +++ /dev/null @@ -1,439 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.assistants.v1.session.message import MessageList - - -class SessionInstance(InstanceResource): - """ - :ivar id: The Session ID. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. - :ivar assistant_id: The Assistant ID. - :ivar verified: True if the session is verified. - :ivar identity: The unique identity of user for the session. - :ivar date_created: The date and time in GMT when the Session was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Session was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], id: Optional[str] = None - ): - super().__init__(version) - - self.id: Optional[str] = payload.get("id") - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.verified: Optional[bool] = payload.get("verified") - self.identity: Optional[str] = payload.get("identity") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - self._solution = { - "id": id or self.id, - } - self._context: Optional[SessionContext] = None - - @property - def _proxy(self) -> "SessionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SessionContext for this SessionInstance - """ - if self._context is None: - self._context = SessionContext( - self._version, - id=self._solution["id"], - ) - return self._context - - def fetch(self) -> "SessionInstance": - """ - Fetch the SessionInstance - - - :returns: The fetched SessionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SessionInstance": - """ - Asynchronous coroutine to fetch the SessionInstance - - - :returns: The fetched SessionInstance - """ - return await self._proxy.fetch_async() - - @property - def messages(self) -> MessageList: - """ - Access the messages - """ - return self._proxy.messages - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class SessionContext(InstanceContext): - - def __init__(self, version: Version, id: str): - """ - Initialize the SessionContext - - :param version: Version that contains the resource - :param id: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "id": id, - } - self._uri = "/Sessions/{id}".format(**self._solution) - - self._messages: Optional[MessageList] = None - - def fetch(self) -> SessionInstance: - """ - Fetch the SessionInstance - - - :returns: The fetched SessionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SessionInstance( - self._version, - payload, - id=self._solution["id"], - ) - - async def fetch_async(self) -> SessionInstance: - """ - Asynchronous coroutine to fetch the SessionInstance - - - :returns: The fetched SessionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SessionInstance( - self._version, - payload, - id=self._solution["id"], - ) - - @property - def messages(self) -> MessageList: - """ - Access the messages - """ - if self._messages is None: - self._messages = MessageList( - self._version, - self._solution["id"], - ) - return self._messages - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class SessionPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: - """ - Build an instance of SessionInstance - - :param payload: Payload response from the API - """ - return SessionInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class SessionList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the SessionList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Sessions" - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SessionInstance]: - """ - Streams SessionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SessionInstance]: - """ - Asynchronously streams SessionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SessionInstance]: - """ - Lists SessionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SessionInstance]: - """ - Asynchronously lists SessionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SessionPage: - """ - Retrieve a single page of SessionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SessionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SessionPage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SessionPage: - """ - Asynchronously retrieve a single page of SessionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SessionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SessionPage(self._version, response) - - def get_page(self, target_url: str) -> SessionPage: - """ - Retrieve a specific page of SessionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SessionInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SessionPage(self._version, response) - - async def get_page_async(self, target_url: str) -> SessionPage: - """ - Asynchronously retrieve a specific page of SessionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SessionInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SessionPage(self._version, response) - - def get(self, id: str) -> SessionContext: - """ - Constructs a SessionContext - - :param id: - """ - return SessionContext(self._version, id=id) - - def __call__(self, id: str) -> SessionContext: - """ - Constructs a SessionContext - - :param id: - """ - return SessionContext(self._version, id=id) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/session/message.py b/twilio/rest/assistants/v1/session/message.py deleted file mode 100644 index a7ea5ca213..0000000000 --- a/twilio/rest/assistants/v1/session/message.py +++ /dev/null @@ -1,309 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class MessageInstance(InstanceResource): - """ - :ivar id: The message ID. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. - :ivar assistant_id: The Assistant ID. - :ivar session_id: The Session ID. - :ivar identity: The identity of the user. - :ivar role: The role of the user associated with the message. - :ivar content: The content of the message. - :ivar meta: The metadata of the message. - :ivar date_created: The date and time in GMT when the Message was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Message was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - """ - - def __init__(self, version: Version, payload: Dict[str, Any], session_id: str): - super().__init__(version) - - self.id: Optional[str] = payload.get("id") - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.session_id: Optional[str] = payload.get("session_id") - self.identity: Optional[str] = payload.get("identity") - self.role: Optional[str] = payload.get("role") - self.content: Optional[Dict[str, object]] = payload.get("content") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - - self._solution = { - "session_id": session_id, - } - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class MessagePage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: - """ - Build an instance of MessageInstance - - :param payload: Payload response from the API - """ - return MessageInstance( - self._version, payload, session_id=self._solution["session_id"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class MessageList(ListResource): - - def __init__(self, version: Version, session_id: str): - """ - Initialize the MessageList - - :param version: Version that contains the resource - :param session_id: Session id or name - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "session_id": session_id, - } - self._uri = "/Sessions/{session_id}/Messages".format(**self._solution) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[MessageInstance]: - """ - Streams MessageInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[MessageInstance]: - """ - Asynchronously streams MessageInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MessageInstance]: - """ - Lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MessageInstance]: - """ - Asynchronously lists MessageInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> MessagePage: - """ - Retrieve a single page of MessageInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of MessageInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return MessagePage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> MessagePage: - """ - Asynchronously retrieve a single page of MessageInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of MessageInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return MessagePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> MessagePage: - """ - Retrieve a specific page of MessageInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MessageInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> MessagePage: - """ - Asynchronously retrieve a specific page of MessageInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MessageInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/assistants/v1/tool.py b/twilio/rest/assistants/v1/tool.py deleted file mode 100644 index 648faca599..0000000000 --- a/twilio/rest/assistants/v1/tool.py +++ /dev/null @@ -1,916 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Assistants - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class ToolInstance(InstanceResource): - - class AssistantsV1ServiceCreatePolicyRequest(object): - """ - :ivar description: The description of the policy. - :ivar id: The Policy ID. - :ivar name: The name of the policy. - :ivar policy_details: - :ivar type: The description of the policy. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.description: Optional[str] = payload.get("description") - self.id: Optional[str] = payload.get("id") - self.name: Optional[str] = payload.get("name") - self.policy_details: Optional[Dict[str, object]] = payload.get( - "policy_details" - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "description": self.description, - "id": self.id, - "name": self.name, - "policy_details": self.policy_details, - "type": self.type, - } - - class AssistantsV1ServiceCreateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The description of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - class AssistantsV1ServiceUpdateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The type of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar id: The tool ID. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar requires_auth: The authentication requirement for the tool. - :ivar type: The type of the tool. ('WEBHOOK') - :ivar url: The url of the tool resource. - :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar policies: The Policies associated with the tool. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], id: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.id: Optional[str] = payload.get("id") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.requires_auth: Optional[bool] = payload.get("requires_auth") - self.type: Optional[str] = payload.get("type") - self.url: Optional[str] = payload.get("url") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.policies: Optional[List[str]] = payload.get("policies") - - self._solution = { - "id": id or self.id, - } - self._context: Optional[ToolContext] = None - - @property - def _proxy(self) -> "ToolContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ToolContext for this ToolInstance - """ - if self._context is None: - self._context = ToolContext( - self._version, - id=self._solution["id"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ToolInstance": - """ - Fetch the ToolInstance - - - :returns: The fetched ToolInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ToolInstance": - """ - Asynchronous coroutine to fetch the ToolInstance - - - :returns: The fetched ToolInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - assistants_v1_service_update_tool_request: Union[ - AssistantsV1ServiceUpdateToolRequest, object - ] = values.unset, - ) -> "ToolInstance": - """ - Update the ToolInstance - - :param assistants_v1_service_update_tool_request: - - :returns: The updated ToolInstance - """ - return self._proxy.update( - assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, - ) - - async def update_async( - self, - assistants_v1_service_update_tool_request: Union[ - AssistantsV1ServiceUpdateToolRequest, object - ] = values.unset, - ) -> "ToolInstance": - """ - Asynchronous coroutine to update the ToolInstance - - :param assistants_v1_service_update_tool_request: - - :returns: The updated ToolInstance - """ - return await self._proxy.update_async( - assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ToolContext(InstanceContext): - - class AssistantsV1ServiceCreatePolicyRequest(object): - """ - :ivar description: The description of the policy. - :ivar id: The Policy ID. - :ivar name: The name of the policy. - :ivar policy_details: - :ivar type: The description of the policy. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.description: Optional[str] = payload.get("description") - self.id: Optional[str] = payload.get("id") - self.name: Optional[str] = payload.get("name") - self.policy_details: Optional[Dict[str, object]] = payload.get( - "policy_details" - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "description": self.description, - "id": self.id, - "name": self.name, - "policy_details": self.policy_details, - "type": self.type, - } - - class AssistantsV1ServiceCreateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The description of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - class AssistantsV1ServiceUpdateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The type of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - def __init__(self, version: Version, id: str): - """ - Initialize the ToolContext - - :param version: Version that contains the resource - :param id: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "id": id, - } - self._uri = "/Tools/{id}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the ToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ToolInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ToolInstance: - """ - Fetch the ToolInstance - - - :returns: The fetched ToolInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ToolInstance( - self._version, - payload, - id=self._solution["id"], - ) - - async def fetch_async(self) -> ToolInstance: - """ - Asynchronous coroutine to fetch the ToolInstance - - - :returns: The fetched ToolInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ToolInstance( - self._version, - payload, - id=self._solution["id"], - ) - - def update( - self, - assistants_v1_service_update_tool_request: Union[ - AssistantsV1ServiceUpdateToolRequest, object - ] = values.unset, - ) -> ToolInstance: - """ - Update the ToolInstance - - :param assistants_v1_service_update_tool_request: - - :returns: The updated ToolInstance - """ - data = assistants_v1_service_update_tool_request.to_dict() - - headers = values.of({}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="PUT", uri=self._uri, data=data, headers=headers - ) - - return ToolInstance(self._version, payload, id=self._solution["id"]) - - async def update_async( - self, - assistants_v1_service_update_tool_request: Union[ - AssistantsV1ServiceUpdateToolRequest, object - ] = values.unset, - ) -> ToolInstance: - """ - Asynchronous coroutine to update the ToolInstance - - :param assistants_v1_service_update_tool_request: - - :returns: The updated ToolInstance - """ - data = assistants_v1_service_update_tool_request.to_dict() - - headers = values.of({}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="PUT", uri=self._uri, data=data, headers=headers - ) - - return ToolInstance(self._version, payload, id=self._solution["id"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ToolPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> ToolInstance: - """ - Build an instance of ToolInstance - - :param payload: Payload response from the API - """ - return ToolInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class ToolList(ListResource): - - class AssistantsV1ServiceCreatePolicyRequest(object): - """ - :ivar description: The description of the policy. - :ivar id: The Policy ID. - :ivar name: The name of the policy. - :ivar policy_details: - :ivar type: The description of the policy. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.description: Optional[str] = payload.get("description") - self.id: Optional[str] = payload.get("id") - self.name: Optional[str] = payload.get("name") - self.policy_details: Optional[Dict[str, object]] = payload.get( - "policy_details" - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "description": self.description, - "id": self.id, - "name": self.name, - "policy_details": self.policy_details, - "type": self.type, - } - - class AssistantsV1ServiceCreateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The description of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - class AssistantsV1ServiceUpdateToolRequest(object): - """ - :ivar assistant_id: The Assistant ID. - :ivar description: The description of the tool. - :ivar enabled: True if the tool is enabled. - :ivar meta: The metadata related to method, url, input_schema to used with the Tool. - :ivar name: The name of the tool. - :ivar policy: - :ivar type: The type of the tool. - """ - - def __init__(self, payload: Dict[str, Any]): - - self.assistant_id: Optional[str] = payload.get("assistant_id") - self.description: Optional[str] = payload.get("description") - self.enabled: Optional[bool] = payload.get("enabled") - self.meta: Optional[Dict[str, object]] = payload.get("meta") - self.name: Optional[str] = payload.get("name") - self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( - payload.get("policy") - ) - self.type: Optional[str] = payload.get("type") - - def to_dict(self): - return { - "assistant_id": self.assistant_id, - "description": self.description, - "enabled": self.enabled, - "meta": self.meta, - "name": self.name, - "policy": self.policy.to_dict() if self.policy is not None else None, - "type": self.type, - } - - def __init__(self, version: Version): - """ - Initialize the ToolList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Tools" - - def create( - self, - assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, - ) -> ToolInstance: - """ - Create the ToolInstance - - :param assistants_v1_service_create_tool_request: - - :returns: The created ToolInstance - """ - data = assistants_v1_service_create_tool_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ToolInstance(self._version, payload) - - async def create_async( - self, - assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, - ) -> ToolInstance: - """ - Asynchronously create the ToolInstance - - :param assistants_v1_service_create_tool_request: - - :returns: The created ToolInstance - """ - data = assistants_v1_service_create_tool_request.to_dict() - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/json" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ToolInstance(self._version, payload) - - def stream( - self, - assistant_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ToolInstance]: - """ - Streams ToolInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param str assistant_id: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - assistant_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[ToolInstance]: - """ - Asynchronously streams ToolInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param str assistant_id: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - assistant_id=assistant_id, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - assistant_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ToolInstance]: - """ - Lists ToolInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str assistant_id: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - assistant_id=assistant_id, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - assistant_id: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ToolInstance]: - """ - Asynchronously lists ToolInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str assistant_id: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - assistant_id=assistant_id, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - assistant_id: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ToolPage: - """ - Retrieve a single page of ToolInstance records from the API. - Request is executed immediately - - :param assistant_id: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ToolInstance - """ - data = values.of( - { - "AssistantId": assistant_id, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ToolPage(self._version, response) - - async def page_async( - self, - assistant_id: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ToolPage: - """ - Asynchronously retrieve a single page of ToolInstance records from the API. - Request is executed immediately - - :param assistant_id: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ToolInstance - """ - data = values.of( - { - "AssistantId": assistant_id, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ToolPage(self._version, response) - - def get_page(self, target_url: str) -> ToolPage: - """ - Retrieve a specific page of ToolInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ToolInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return ToolPage(self._version, response) - - async def get_page_async(self, target_url: str) -> ToolPage: - """ - Asynchronously retrieve a specific page of ToolInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ToolInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return ToolPage(self._version, response) - - def get(self, id: str) -> ToolContext: - """ - Constructs a ToolContext - - :param id: - """ - return ToolContext(self._version, id=id) - - def __call__(self, id: str) -> ToolContext: - """ - Constructs a ToolContext - - :param id: - """ - return ToolContext(self._version, id=id) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/bulkexports/v1/export/__init__.py b/twilio/rest/bulkexports/v1/export/__init__.py index 0ebf3a451b..2bb449d2a4 100644 --- a/twilio/rest/bulkexports/v1/export/__init__.py +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportContext] = None @property @@ -81,6 +83,24 @@ async def fetch_async(self) -> "ExportInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def days(self) -> DayList: """ @@ -125,48 +145,96 @@ def __init__(self, version: Version, resource_type: str): self._days: Optional[DayList] = None self._export_custom_jobs: Optional[ExportCustomJobList] = None - def fetch(self) -> ExportInstance: + def _fetch(self) -> tuple: """ - Fetch the ExportInstance + Internal helper for fetch operation - - :returns: The fetched ExportInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ExportInstance: + """ + Fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + payload, _, _ = self._fetch() return ExportInstance( self._version, payload, resource_type=self._solution["resource_type"], ) - async def fetch_async(self) -> ExportInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExportInstance + Fetch the ExportInstance and return response metadata - :returns: The fetched ExportInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExportInstance: + """ + Asynchronous coroutine to fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + payload, _, _ = await self._fetch_async() return ExportInstance( self._version, payload, resource_type=self._solution["resource_type"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def days(self) -> DayList: """ diff --git a/twilio/rest/bulkexports/v1/export/day.py b/twilio/rest/bulkexports/v1/export/day.py index f4b2a0650f..b19395fde5 100644 --- a/twilio/rest/bulkexports/v1/export/day.py +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "resource_type": resource_type, "day": day or self.day, } + self._context: Optional[DayContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "DayInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DayInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DayInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -116,20 +136,30 @@ def __init__(self, version: Version, resource_type: str, day: str): } self._uri = "/Exports/{resource_type}/Days/{day}".format(**self._solution) - def fetch(self) -> DayInstance: + def _fetch(self) -> tuple: """ - Fetch the DayInstance - + Internal helper for fetch operation - :returns: The fetched DayInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DayInstance: + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance + """ + payload, _, _ = self._fetch() return DayInstance( self._version, payload, @@ -137,22 +167,46 @@ def fetch(self) -> DayInstance: day=self._solution["day"], ) - async def fetch_async(self) -> DayInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DayInstance + Fetch the DayInstance and return response metadata - :returns: The fetched DayInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DayInstance: + """ + Asynchronous coroutine to fetch the DayInstance + + + :returns: The fetched DayInstance + """ + payload, _, _ = await self._fetch_async() return DayInstance( self._version, payload, @@ -160,6 +214,22 @@ async def fetch_async(self) -> DayInstance: day=self._solution["day"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DayInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -178,6 +248,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DayInstance: :param payload: Payload response from the API """ + return DayInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -259,6 +330,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DayInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DayInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -278,6 +399,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -304,6 +426,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -312,6 +435,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DayInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DayInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -343,7 +516,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DayPage(self._version, response, self._solution) + return DayPage(self._version, response, solution=self._solution) async def page_async( self, @@ -376,7 +549,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DayPage(self._version, response, self._solution) + return DayPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DayPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DayPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DayPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DayPage: """ @@ -388,7 +631,7 @@ def get_page(self, target_url: str) -> DayPage: :returns: Page of DayInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DayPage(self._version, response, self._solution) + return DayPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DayPage: """ @@ -400,7 +643,7 @@ async def get_page_async(self, target_url: str) -> DayPage: :returns: Page of DayInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DayPage(self._version, response, self._solution) + return DayPage(self._version, response, solution=self._solution) def get(self, day: str) -> DayContext: """ diff --git a/twilio/rest/bulkexports/v1/export/export_custom_job.py b/twilio/rest/bulkexports/v1/export/export_custom_job.py index 72d0e9b328..dee11094c1 100644 --- a/twilio/rest/bulkexports/v1/export/export_custom_job.py +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], resource_type: str self.webhook_method: Optional[str] = payload.get("webhook_method") self.email: Optional[str] = payload.get("email") self.job_sid: Optional[str] = payload.get("job_sid") - self.details: Optional[Dict[str, object]] = payload.get("details") + self.details: Optional[List[Dict[str, object]]] = payload.get("details") self.job_queue_position: Optional[str] = payload.get("job_queue_position") self.estimated_completion_time: Optional[str] = payload.get( "estimated_completion_time" @@ -75,6 +76,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: :param payload: Payload response from the API """ + return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -106,7 +108,7 @@ def __init__(self, version: Version, resource_type: str): } self._uri = "/Exports/{resource_type}/Jobs".format(**self._solution) - def create( + def _create( self, start_day: str, end_day: str, @@ -114,18 +116,12 @@ def create( webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> ExportCustomJobInstance: + ) -> tuple: """ - Create the ExportCustomJobInstance - - :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd - :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. - :param friendly_name: The friendly name specified when creating the job - :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. - :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. - :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + Internal helper for create operation - :returns: The created ExportCustomJobInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -144,15 +140,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) - async def create_async( + def create_with_http_info( self, start_day: str, end_day: str, @@ -160,9 +185,9 @@ async def create_async( webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> ExportCustomJobInstance: + ) -> ApiResponse: """ - Asynchronously create the ExportCustomJobInstance + Create the ExportCustomJobInstance and return response metadata :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. @@ -171,7 +196,35 @@ async def create_async( :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. - :returns: The created ExportCustomJobInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -190,14 +243,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Asynchronously create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) + async def create_with_http_info_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ExportCustomJobInstance and return response metadata + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -248,6 +364,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ExportCustomJobInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ExportCustomJobInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -267,6 +433,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -293,6 +460,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -301,6 +469,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ExportCustomJobInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ExportCustomJobInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -332,7 +550,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ExportCustomJobPage(self._version, response, self._solution) + return ExportCustomJobPage(self._version, response, solution=self._solution) async def page_async( self, @@ -365,7 +583,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ExportCustomJobPage(self._version, response, self._solution) + return ExportCustomJobPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExportCustomJobPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExportCustomJobPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExportCustomJobPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExportCustomJobPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ExportCustomJobPage: """ @@ -377,7 +665,7 @@ def get_page(self, target_url: str) -> ExportCustomJobPage: :returns: Page of ExportCustomJobInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ExportCustomJobPage(self._version, response, self._solution) + return ExportCustomJobPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ExportCustomJobPage: """ @@ -389,7 +677,7 @@ async def get_page_async(self, target_url: str) -> ExportCustomJobPage: :returns: Page of ExportCustomJobInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ExportCustomJobPage(self._version, response, self._solution) + return ExportCustomJobPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/bulkexports/v1/export/job.py b/twilio/rest/bulkexports/v1/export/job.py index 5358ffa83a..2f8a7ef8f9 100644 --- a/twilio/rest/bulkexports/v1/export/job.py +++ b/twilio/rest/bulkexports/v1/export/job.py @@ -12,8 +12,9 @@ Do not edit the class manually. """ -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -43,7 +44,7 @@ def __init__( self.resource_type: Optional[str] = payload.get("resource_type") self.friendly_name: Optional[str] = payload.get("friendly_name") - self.details: Optional[Dict[str, object]] = payload.get("details") + self.details: Optional[List[Dict[str, object]]] = payload.get("details") self.start_day: Optional[str] = payload.get("start_day") self.end_day: Optional[str] = payload.get("end_day") self.job_sid: Optional[str] = payload.get("job_sid") @@ -59,6 +60,7 @@ def __init__( self._solution = { "job_sid": job_sid or self.job_sid, } + self._context: Optional[JobContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the JobInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the JobInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "JobInstance": """ Fetch the JobInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "JobInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the JobInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the JobInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -139,6 +177,20 @@ def __init__(self, version: Version, job_sid: str): } self._uri = "/Exports/Jobs/{job_sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the JobInstance @@ -146,10 +198,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the JobInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -158,55 +232,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the JobInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> JobInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the JobInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched JobInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> JobInstance: + """ + Fetch the JobInstance + + + :returns: The fetched JobInstance + """ + payload, _, _ = self._fetch() return JobInstance( self._version, payload, job_sid=self._solution["job_sid"], ) - async def fetch_async(self) -> JobInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the JobInstance + Fetch the JobInstance and return response metadata - :returns: The fetched JobInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> JobInstance: + """ + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance + """ + payload, _, _ = await self._fetch_async() return JobInstance( self._version, payload, job_sid=self._solution["job_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the JobInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/bulkexports/v1/export_configuration.py b/twilio/rest/bulkexports/v1/export_configuration.py index 207642769b..d5b684b092 100644 --- a/twilio/rest/bulkexports/v1/export_configuration.py +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportConfigurationContext] = None @property @@ -81,6 +83,24 @@ async def fetch_async(self) -> "ExportConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, enabled: Union[bool, object] = values.unset, @@ -123,6 +143,48 @@ async def update_async( webhook_method=webhook_method, ) + def update_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ExportConfigurationInstance with HTTP info + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + async def update_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExportConfigurationInstance with HTTP info + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,62 +212,107 @@ def __init__(self, version: Version, resource_type: str): } self._uri = "/Exports/{resource_type}/Configuration".format(**self._solution) - def fetch(self) -> ExportConfigurationInstance: + def _fetch(self) -> tuple: """ - Fetch the ExportConfigurationInstance - + Internal helper for fetch operation - :returns: The fetched ExportConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ExportConfigurationInstance: + """ + Fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + payload, _, _ = self._fetch() return ExportConfigurationInstance( self._version, payload, resource_type=self._solution["resource_type"], ) - async def fetch_async(self) -> ExportConfigurationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExportConfigurationInstance + Fetch the ExportConfigurationInstance and return response metadata - :returns: The fetched ExportConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return ExportConfigurationInstance( self._version, payload, resource_type=self._solution["resource_type"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, enabled: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, - ) -> ExportConfigurationInstance: + ) -> tuple: """ - Update the ExportConfigurationInstance + Internal helper for update operation - :param enabled: If true, Twilio will automatically generate every day's file when the day is over. - :param webhook_url: Stores the URL destination for the method specified in webhook_method. - :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url - - :returns: The updated ExportConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -221,28 +328,66 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + payload, _, _ = self._update( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) return ExportConfigurationInstance( self._version, payload, resource_type=self._solution["resource_type"] ) - async def update_async( + def update_with_http_info( self, enabled: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, - ) -> ExportConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ExportConfigurationInstance + Update the ExportConfigurationInstance and return response metadata :param enabled: If true, Twilio will automatically generate every day's file when the day is over. :param webhook_url: Stores the URL destination for the method specified in webhook_method. :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url - :returns: The updated ExportConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + instance = ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -258,14 +403,55 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + payload, _, _ = await self._update_async( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) return ExportConfigurationInstance( self._version, payload, resource_type=self._solution["resource_type"] ) + async def update_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExportConfigurationInstance and return response metadata + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method + ) + instance = ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/chat/v1/credential.py b/twilio/rest/chat/v1/credential.py index 3bd48b1144..a5d48dc68b 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,56 +354,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -277,18 +465,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -307,13 +489,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -323,7 +503,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` @@ -334,6 +514,63 @@ async def update_async( :returns: The updated CredentialInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +588,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -375,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -399,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -408,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance - - :param type: - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -440,13 +732,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -457,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -469,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -487,12 +839,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -543,6 +962,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -562,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -588,6 +1058,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -596,6 +1067,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -662,6 +1183,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/chat/v1/service/__init__.py b/twilio/rest/chat/v1/service/__init__.py index 26fde4025b..2d4c6b097d 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -129,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -147,6 +167,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -495,127 +533,7 @@ async def update_async( limits_user_channels=limits_user_channels, ) - @property - def channels(self) -> ChannelList: - """ - Access the channels - """ - return self._proxy.channels - - @property - def roles(self) -> RoleList: - """ - Access the roles - """ - return self._proxy.roles - - @property - def users(self) -> UserList: - """ - Access the users - """ - return self._proxy.users - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ServiceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the ServiceContext - - :param version: Version that contains the resource - :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Services/{sid}".format(**self._solution) - - self._channels: Optional[ChannelList] = None - self._roles: Optional[RoleList] = None - self._users: Optional[UserList] = None - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ServiceInstance: - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -671,9 +589,9 @@ def update( webhooks_on_member_removed_method: Union[str, object] = values.unset, limits_channel_members: Union[int, object] = values.unset, limits_user_channels: Union[int, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Update the ServiceInstance + Update the ServiceInstance with HTTP info :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. @@ -730,69 +648,1066 @@ def update( :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, @@ -807,12 +1722,10 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, friendly_name: Union[str, object] = values.unset, @@ -930,86 +1843,239 @@ async def update_async( :returns: The updated ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, - "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, - "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, - "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, - "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, ) - headers = values.of({}) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata - headers["Accept"] = "application/json" + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def channels(self) -> ChannelList: @@ -1065,6 +2131,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -1089,13 +2156,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1109,19 +2175,39 @@ def create(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return ServiceInstance(self._version, payload) - async def create_async(self, friendly_name: str) -> ServiceInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1135,12 +2221,35 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ServiceInstance(self._version, payload) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -1191,6 +2300,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -1210,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1236,6 +2396,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1244,6 +2405,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1310,6 +2521,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/chat/v1/service/channel/__init__.py b/twilio/rest/chat/v1/service/channel/__init__.py index ffe42c0b5d..d65a59603b 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -180,6 +218,48 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + @property def invites(self) -> InviteList: """ @@ -234,6 +314,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._members: Optional[MemberList] = None self._messages: Optional[MessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -241,10 +335,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -253,27 +369,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() return ChannelInstance( self._version, payload, @@ -281,22 +413,46 @@ def fetch(self) -> ChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelInstance + Fetch the ChannelInstance and return response metadata - :returns: The fetched ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() return ChannelInstance( self._version, payload, @@ -304,20 +460,33 @@ async def fetch_async(self) -> ChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Update the ChannelInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -333,10 +502,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, @@ -344,20 +531,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ChannelInstance + Update the ChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. :param attributes: A valid JSON string that contains application-specific data. - :returns: The updated ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -373,10 +583,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, @@ -384,6 +612,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def invites(self) -> InviteList: """ @@ -441,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -472,22 +727,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - :param type: - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -504,30 +755,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. :param attributes: A valid JSON string that contains application-specific data. :param type: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -544,14 +842,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -606,6 +955,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -627,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -656,6 +1062,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -665,6 +1072,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -699,7 +1162,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -735,7 +1198,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChannelPage: """ @@ -747,7 +1286,7 @@ def get_page(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelPage: """ @@ -759,7 +1298,7 @@ async def get_page_async(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelContext: """ diff --git a/twilio/rest/chat/v1/service/channel/invite.py b/twilio/rest/chat/v1/service/channel/invite.py index e5cd4ebe36..d88124ec63 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,10 +215,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -175,27 +249,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InviteInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InviteInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InviteInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() return InviteInstance( self._version, payload, @@ -204,22 +294,47 @@ def fetch(self) -> InviteInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InviteInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InviteInstance + Fetch the InviteInstance and return response metadata - :returns: The fetched InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() return InviteInstance( self._version, payload, @@ -228,6 +343,23 @@ async def fetch_async(self) -> InviteInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -284,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. - - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +439,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -319,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,10 +506,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -354,6 +529,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -408,6 +605,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -429,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -458,6 +712,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -467,6 +722,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -501,7 +812,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -537,7 +848,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InvitePage: """ @@ -549,7 +936,7 @@ def get_page(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InvitePage: """ @@ -561,7 +948,7 @@ async def get_page_async(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) def get(self, sid: str) -> InviteContext: """ diff --git a/twilio/rest/chat/v1/service/channel/member.py b/twilio/rest/chat/v1/service/channel/member.py index 1262703ddc..392847cb06 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -163,6 +201,42 @@ async def update_async( last_consumed_message_index=last_consumed_message_index, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +272,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MemberInstance @@ -205,10 +293,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -217,27 +327,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MemberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MemberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MemberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() return MemberInstance( self._version, payload, @@ -246,22 +372,47 @@ def fetch(self) -> MemberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MemberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MemberInstance + Fetch the MemberInstance and return response metadata - :returns: The fetched MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -270,18 +421,33 @@ async def fetch_async(self) -> MemberInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, role_sid: Union[str, object] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Update the MemberInstance - - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). - :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + Internal helper for update operation - :returns: The updated MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,10 +462,26 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + payload, _, _ = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) return MemberInstance( self._version, payload, @@ -308,18 +490,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, role_sid: Union[str, object] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MemberInstance + Update the MemberInstance and return response metadata :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). - :returns: The updated MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -334,10 +539,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) return MemberInstance( self._version, payload, @@ -346,6 +567,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -364,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -402,16 +649,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -426,10 +671,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return MemberInstance( self._version, payload, @@ -437,16 +694,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -461,10 +738,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return MemberInstance( self._version, payload, @@ -472,6 +761,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -526,6 +837,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -547,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -576,6 +944,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -585,6 +954,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -619,7 +1044,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -655,7 +1080,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MemberPage: """ @@ -667,7 +1168,7 @@ def get_page(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MemberPage: """ @@ -679,7 +1180,7 @@ async def get_page_async(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MemberContext: """ diff --git a/twilio/rest/chat/v1/service/channel/message.py b/twilio/rest/chat/v1/service/channel/message.py index e7cfc9217d..11824c42ed 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -168,6 +206,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +277,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -210,10 +298,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -222,27 +332,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -251,22 +377,47 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -275,18 +426,33 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, body: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance + Internal helper for update operation - :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -301,10 +467,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + payload, _, _ = self._update(body=body, attributes=attributes) return MessageInstance( self._version, payload, @@ -313,18 +493,39 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, body: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance and return response metadata :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. :param attributes: A valid JSON string that contains application-specific data. - :returns: The updated MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body, attributes=attributes) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -339,10 +540,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async(body=body, attributes=attributes) return MessageInstance( self._version, payload, @@ -351,6 +566,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + body=body, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -369,6 +609,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -407,20 +648,17 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. - :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -436,10 +674,26 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + payload, _, _ = self._create(body=body, from_=from_, attributes=attributes) return MessageInstance( self._version, payload, @@ -447,20 +701,43 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. :param attributes: A valid JSON string that contains application-specific data. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -476,10 +753,28 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + body=body, from_=from_, attributes=attributes + ) return MessageInstance( self._version, payload, @@ -487,6 +782,32 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -541,6 +862,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -562,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -591,6 +969,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -600,6 +979,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -634,7 +1069,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -670,7 +1105,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -682,7 +1193,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -694,7 +1205,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/chat/v1/service/role.py b/twilio/rest/chat/v1/service/role.py index d81cbd55ac..a17f74eb7c 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,10 +257,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -193,27 +291,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, @@ -221,22 +335,46 @@ def fetch(self) -> RoleInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -244,13 +382,28 @@ async def fetch_async(self) -> RoleInstance: sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +417,19 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -275,13 +437,29 @@ def update(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +473,19 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance( self._version, payload, @@ -306,6 +493,23 @@ async def update_async(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -324,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -355,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,25 +583,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +649,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -492,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -526,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -557,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -590,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RolePage: """ @@ -602,7 +1043,7 @@ def get_page(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RolePage: """ @@ -614,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleContext: """ diff --git a/twilio/rest/chat/v1/service/user/__init__.py b/twilio/rest/chat/v1/service/user/__init__.py index c6b900957c..69a785ce4f 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -171,6 +209,48 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_channels(self) -> UserChannelList: """ @@ -209,6 +289,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -216,10 +310,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -228,27 +344,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, @@ -256,22 +388,46 @@ def fetch(self) -> UserInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -279,20 +435,33 @@ async def fetch_async(self) -> UserInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance + Internal helper for update operation - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. - :param attributes: A valid JSON string that contains application-specific data. - :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +477,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + payload, _, _ = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) return UserInstance( self._version, payload, @@ -319,20 +506,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance and return response metadata :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -348,10 +558,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) return UserInstance( self._version, payload, @@ -359,6 +587,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def user_channels(self) -> UserChannelList: """ @@ -390,6 +644,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -421,22 +676,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. - :param attributes: A valid JSON string that contains application-specific data. - :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -453,30 +704,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,14 +791,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -551,6 +900,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -570,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,6 +996,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -604,6 +1005,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -635,7 +1086,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -668,7 +1119,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -680,7 +1201,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -692,7 +1213,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserContext: """ diff --git a/twilio/rest/chat/v1/service/user/user_channel.py b/twilio/rest/chat/v1/service/user/user_channel.py index b7f35aa9ef..604cbddec5 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -170,6 +172,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -189,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -215,6 +268,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +277,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -254,7 +358,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -287,7 +391,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserChannelPage: """ @@ -299,7 +473,7 @@ def get_page(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserChannelPage: """ @@ -311,7 +485,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/chat/v2/credential.py b/twilio/rest/chat/v2/credential.py index 5479abeca0..40c972a9c2 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,56 +354,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -277,18 +465,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -307,13 +489,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -323,7 +503,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` @@ -334,6 +514,63 @@ async def update_async( :returns: The updated CredentialInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +588,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -375,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -399,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -408,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance - - :param type: - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -440,13 +732,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -457,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -469,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -487,12 +839,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -543,6 +962,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -562,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -588,6 +1058,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -596,6 +1067,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -662,6 +1183,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/chat/v2/service/__init__.py b/twilio/rest/chat/v2/service/__init__.py index 90a6c6cdba..de0bab251a 100644 --- a/twilio/rest/chat/v2/service/__init__.py +++ b/twilio/rest/chat/v2/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -103,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -370,135 +408,7 @@ async def update_async( notifications_log_enabled=notifications_log_enabled, ) - @property - def bindings(self) -> BindingList: - """ - Access the bindings - """ - return self._proxy.bindings - - @property - def channels(self) -> ChannelList: - """ - Access the channels - """ - return self._proxy.channels - - @property - def roles(self) -> RoleList: - """ - Access the roles - """ - return self._proxy.roles - - @property - def users(self) -> UserList: - """ - Access the users - """ - return self._proxy.users - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ServiceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the ServiceContext - - :param version: Version that contains the resource - :param sid: The SID of the Service resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Services/{sid}".format(**self._solution) - - self._bindings: Optional[BindingList] = None - self._channels: Optional[ChannelList] = None - self._roles: Optional[RoleList] = None - self._users: Optional[UserList] = None - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ServiceInstance: - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -533,9 +443,9 @@ def update( pre_webhook_retry_count: Union[int, object] = values.unset, post_webhook_retry_count: Union[int, object] = values.unset, notifications_log_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Update the ServiceInstance + Update the ServiceInstance with HTTP info :param friendly_name: A descriptive string that you create to describe the resource. :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. @@ -569,71 +479,43 @@ def update( :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. :param notifications_log_enabled: Whether to log notifications. The default is `false`. - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( - notifications_new_message_badge_count_enabled - ), - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - "Media.CompatibilityMessage": media_compatibility_message, - "PreWebhookRetryCount": pre_webhook_retry_count, - "PostWebhookRetryCount": post_webhook_retry_count, - "Notifications.LogEnabled": serialize.boolean_to_string( - notifications_log_enabled - ), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + async def update_with_http_info_async( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -668,9 +550,9 @@ async def update_async( pre_webhook_retry_count: Union[int, object] = values.unset, post_webhook_retry_count: Union[int, object] = values.unset, notifications_log_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ServiceInstance + Asynchronous coroutine to update the ServiceInstance with HTTP info :param friendly_name: A descriptive string that you create to describe the resource. :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. @@ -704,21 +586,634 @@ async def update_async( :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. :param notifications_log_enabled: Whether to log notifications. The default is `false`. - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, "Notifications.NewMessage.Enabled": serialize.boolean_to_string( notifications_new_message_enabled ), @@ -760,13 +1255,228 @@ async def update_async( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def bindings(self) -> BindingList: @@ -834,6 +1544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -858,13 +1569,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -878,19 +1588,39 @@ def create(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return ServiceInstance(self._version, payload) - async def create_async(self, friendly_name: str) -> ServiceInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -904,12 +1634,35 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ServiceInstance(self._version, payload) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -960,6 +1713,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -979,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1005,6 +1809,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1013,6 +1818,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1079,6 +1934,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/chat/v2/service/binding.py b/twilio/rest/chat/v2/service/binding.py index 125f4b9368..cd5b0d1dc0 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +197,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,10 +218,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -178,27 +252,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = self._fetch() return BindingInstance( self._version, payload, @@ -206,22 +296,46 @@ def fetch(self) -> BindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> BindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BindingInstance + Fetch the BindingInstance and return response metadata - :returns: The fetched BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() return BindingInstance( self._version, payload, @@ -229,6 +343,22 @@ async def fetch_async(self) -> BindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,6 +377,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -340,6 +471,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -363,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -395,6 +587,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -405,6 +598,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -442,7 +697,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -481,7 +736,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BindingPage: """ @@ -493,7 +830,7 @@ def get_page(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BindingPage: """ @@ -505,7 +842,7 @@ async def get_page_async(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> BindingContext: """ diff --git a/twilio/rest/chat/v2/service/channel/__init__.py b/twilio/rest/chat/v2/service/channel/__init__.py index 36d08a3896..d2c4bf396c 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -141,6 +143,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -159,6 +195,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -229,6 +283,76 @@ async def update_async( created_by=created_by, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + @property def invites(self) -> InviteList: """ @@ -291,6 +415,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._messages: Optional[MessageList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -304,6 +452,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -312,7 +493,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -327,32 +510,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() return ChannelInstance( self._version, payload, @@ -360,22 +564,46 @@ def fetch(self) -> ChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelInstance + Fetch the ChannelInstance and return response metadata - :returns: The fetched ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() return ChannelInstance( self._version, payload, @@ -383,7 +611,23 @@ async def fetch_async(self) -> ChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -394,19 +638,12 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Update the ChannelInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. - :param created_by: The `identity` of the User that created the channel. Default is: `system`. + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -434,18 +671,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ChannelInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -458,7 +688,7 @@ async def update_async( created_by: Union[str, object] = values.unset, ) -> ChannelInstance: """ - Asynchronous coroutine to update the ChannelInstance + Update the ChannelInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. @@ -470,36 +700,15 @@ async def update_async( :returns: The updated ChannelInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "CreatedBy": created_by, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, ) - return ChannelInstance( self._version, payload, @@ -507,14 +716,187 @@ async def update_async( sid=self._solution["sid"], ) - @property - def invites(self) -> InviteList: - """ - Access the invites - """ - if self._invites is None: - self._invites = InviteList( - self._version, + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, self._solution["service_sid"], self._solution["sid"], ) @@ -577,6 +959,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -608,7 +991,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -620,20 +1003,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - :param type: - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. - :param created_by: The `identity` of the User that created the channel. Default is: `system`. - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -658,15 +1033,52 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -678,9 +1090,9 @@ async def create_async( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -691,7 +1103,41 @@ async def create_async( :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. :param created_by: The `identity` of the User that created the channel. Default is: `system`. - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -716,14 +1162,93 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -778,6 +1303,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -799,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -828,6 +1410,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -837,6 +1420,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -871,7 +1510,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -907,7 +1546,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChannelPage: """ @@ -919,7 +1634,7 @@ def get_page(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelPage: """ @@ -931,7 +1646,7 @@ async def get_page_async(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelContext: """ diff --git a/twilio/rest/chat/v2/service/channel/invite.py b/twilio/rest/chat/v2/service/channel/invite.py index 7c7f9f6211..1a3be5b92a 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,10 +215,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -175,27 +249,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InviteInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InviteInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InviteInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() return InviteInstance( self._version, payload, @@ -204,22 +294,47 @@ def fetch(self) -> InviteInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InviteInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InviteInstance + Fetch the InviteInstance and return response metadata - :returns: The fetched InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() return InviteInstance( self._version, payload, @@ -228,6 +343,23 @@ async def fetch_async(self) -> InviteInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -284,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. - - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +439,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -319,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,10 +506,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -354,6 +529,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -408,6 +605,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -429,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -458,6 +712,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -467,6 +722,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InviteInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -501,7 +812,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -537,7 +848,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InvitePage: """ @@ -549,7 +936,7 @@ def get_page(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InvitePage: """ @@ -561,7 +948,7 @@ async def get_page_async(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) def get(self, sid: str) -> InviteContext: """ diff --git a/twilio/rest/chat/v2/service/channel/member.py b/twilio/rest/chat/v2/service/channel/member.py index f07cb21891..9e40454a44 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -132,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -150,6 +186,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -220,6 +274,76 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -255,6 +379,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -268,6 +416,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -276,7 +457,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -291,32 +474,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MemberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MemberInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MemberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() return MemberInstance( self._version, payload, @@ -325,22 +529,47 @@ def fetch(self) -> MemberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MemberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MemberInstance + Fetch the MemberInstance and return response metadata - :returns: The fetched MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -349,7 +578,24 @@ async def fetch_async(self) -> MemberInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -360,19 +606,12 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Update the MemberInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). - :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). - :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. - :param attributes: A valid JSON string that contains application-specific data. + Internal helper for update operation - :returns: The updated MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -402,19 +641,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MemberInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -427,7 +658,7 @@ async def update_async( attributes: Union[str, object] = values.unset, ) -> MemberInstance: """ - Asynchronous coroutine to update the MemberInstance + Update the MemberInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). @@ -439,38 +670,15 @@ async def update_async( :returns: The updated MemberInstance """ - - data = values.of( - { - "RoleSid": role_sid, - "LastConsumedMessageIndex": last_consumed_message_index, - "LastConsumptionTimestamp": serialize.iso8601_datetime( - last_consumption_timestamp - ), - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, ) - return MemberInstance( self._version, payload, @@ -479,9 +687,187 @@ async def update_async( sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation :returns: Machine friendly representation """ @@ -497,6 +883,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -535,7 +922,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -547,20 +934,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). - :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. - :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -587,10 +966,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) return MemberInstance( self._version, payload, @@ -598,7 +1014,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -610,9 +1026,9 @@ async def create_async( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -623,7 +1039,44 @@ async def create_async( :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. :param attributes: A valid JSON string that contains application-specific data. - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -650,10 +1103,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) return MemberInstance( self._version, payload, @@ -661,6 +1151,51 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -715,6 +1250,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -736,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -765,6 +1357,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -774,6 +1367,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MemberInstance and returns headers from first page + + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -808,7 +1457,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -844,7 +1493,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MemberPage: """ @@ -856,7 +1581,7 @@ def get_page(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MemberPage: """ @@ -868,7 +1593,7 @@ async def get_page_async(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MemberContext: """ diff --git a/twilio/rest/chat/v2/service/channel/message.py b/twilio/rest/chat/v2/service/channel/message.py index d0bf2e5ac7..ee6de8ed3d 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -140,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -158,6 +194,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -228,6 +282,76 @@ async def update_async( from_=from_, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -263,6 +387,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -276,6 +424,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -284,7 +465,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -299,32 +482,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -333,22 +537,47 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -357,7 +586,24 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -368,19 +614,12 @@ def update( date_updated: Union[datetime, object] = values.unset, last_updated_by: Union[str, object] = values.unset, from_: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. - :param attributes: A valid JSON string that contains application-specific data. - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. - :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. - :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,19 +647,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MessageInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -433,7 +664,7 @@ async def update_async( from_: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. @@ -445,36 +676,15 @@ async def update_async( :returns: The updated MessageInstance """ - - data = values.of( - { - "Body": body, - "Attributes": attributes, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "LastUpdatedBy": last_updated_by, - "From": from_, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, ) - return MessageInstance( self._version, payload, @@ -483,11 +693,187 @@ async def update_async( sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -501,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -539,7 +926,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -551,20 +938,12 @@ def create( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. - :param attributes: A valid JSON string that contains application-specific data. - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. - :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. - :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. - :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -589,10 +968,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) return MessageInstance( self._version, payload, @@ -600,7 +1016,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -612,9 +1028,9 @@ async def create_async( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. @@ -625,7 +1041,44 @@ async def create_async( :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -650,10 +1103,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) return MessageInstance( self._version, payload, @@ -661,6 +1151,51 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -715,6 +1250,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -736,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -765,6 +1357,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -774,6 +1367,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -808,7 +1457,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -844,7 +1493,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -856,7 +1581,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -868,7 +1593,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/chat/v2/service/channel/webhook.py b/twilio/rest/chat/v2/service/channel/webhook.py index 3e31df4288..f5372f3595 100644 --- a/twilio/rest/chat/v2/service/channel/webhook.py +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -189,6 +227,66 @@ async def update_async( configuration_retry_count=configuration_retry_count, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,6 +322,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -231,10 +343,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -243,27 +377,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebhookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebhookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, @@ -272,22 +422,47 @@ def fetch(self) -> WebhookInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, @@ -296,7 +471,24 @@ async def fetch_async(self) -> WebhookInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -304,18 +496,12 @@ def update( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance + Internal helper for update operation - :param configuration_url: The URL of the webhook to call using the `configuration.method`. - :param configuration_method: - :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). - :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. - :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. - :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -338,10 +524,39 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -350,7 +565,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -358,9 +573,9 @@ async def update_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param configuration_url: The URL of the webhook to call using the `configuration.method`. :param configuration_method: @@ -369,7 +584,39 @@ async def update_async( :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -392,10 +639,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -404,6 +680,44 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -422,6 +736,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, @@ -460,7 +775,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, type: "WebhookInstance.Type", configuration_url: Union[str, object] = values.unset, @@ -469,19 +784,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param type: - :param configuration_url: The URL of the webhook to call using the `configuration.method`. - :param configuration_method: - :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). - :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. - :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. - :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -505,10 +813,42 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -516,7 +856,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, type: "WebhookInstance.Type", configuration_url: Union[str, object] = values.unset, @@ -525,9 +865,9 @@ async def create_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param type: :param configuration_url: The URL of the webhook to call using the `configuration.method`. @@ -537,7 +877,40 @@ async def create_async( :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -561,10 +934,42 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -572,6 +977,46 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -622,6 +1067,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -641,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -667,6 +1163,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -675,6 +1172,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -706,7 +1253,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -739,7 +1286,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WebhookPage: """ @@ -751,7 +1368,7 @@ def get_page(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WebhookPage: """ @@ -763,7 +1380,7 @@ async def get_page_async(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WebhookContext: """ diff --git a/twilio/rest/chat/v2/service/role.py b/twilio/rest/chat/v2/service/role.py index fef06436d0..3c6fff8f9c 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,10 +257,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -193,27 +291,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, @@ -221,22 +335,46 @@ def fetch(self) -> RoleInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -244,13 +382,28 @@ async def fetch_async(self) -> RoleInstance: sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +417,19 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -275,13 +437,29 @@ def update(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +473,19 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance( self._version, payload, @@ -306,6 +493,23 @@ async def update_async(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -324,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -355,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,25 +583,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +649,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -492,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -526,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -557,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -590,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RolePage: """ @@ -602,7 +1043,7 @@ def get_page(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RolePage: """ @@ -614,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleContext: """ diff --git a/twilio/rest/chat/v2/service/user/__init__.py b/twilio/rest/chat/v2/service/user/__init__.py index 9fbde6feda..b31d666b71 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -117,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -135,6 +155,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -187,6 +225,58 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_bindings(self) -> UserBindingList: """ @@ -233,6 +323,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_bindings: Optional[UserBindingList] = None self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -240,10 +344,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -252,27 +378,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, @@ -280,22 +422,46 @@ def fetch(self) -> UserInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -303,7 +469,23 @@ async def fetch_async(self) -> UserInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -311,16 +493,12 @@ def update( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. - :param attributes: A valid JSON string that contains application-specific data. - :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + Internal helper for update operation - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -345,10 +523,35 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, @@ -356,7 +559,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -364,16 +567,45 @@ async def update_async( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -398,10 +630,35 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, @@ -409,6 +666,39 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def user_bindings(self) -> UserBindingList: """ @@ -453,6 +743,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -484,7 +775,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -493,17 +784,12 @@ def create( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. - :param attributes: A valid JSON string that contains application-specific data. - :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -525,15 +811,43 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -542,9 +856,9 @@ async def create_async( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -552,7 +866,35 @@ async def create_async( :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -574,14 +916,75 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -632,6 +1035,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -651,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -677,6 +1131,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -685,6 +1140,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -716,7 +1221,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -749,7 +1254,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -761,7 +1336,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -773,7 +1348,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserContext: """ diff --git a/twilio/rest/chat/v2/service/user/user_binding.py b/twilio/rest/chat/v2/service/user/user_binding.py index 8d79c551af..9d9ae604ef 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "user_sid": user_sid, "sid": sid or self.sid, } + self._context: Optional[UserBindingContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserBindingInstance": """ Fetch the UserBindingInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "UserBindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserBindingInstance @@ -173,10 +225,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -185,27 +259,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserBindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserBindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserBindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + payload, _, _ = self._fetch() return UserBindingInstance( self._version, payload, @@ -214,22 +304,47 @@ def fetch(self) -> UserBindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserBindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserBindingInstance + Fetch the UserBindingInstance and return response metadata - :returns: The fetched UserBindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + payload, _, _ = await self._fetch_async() return UserBindingInstance( self._version, payload, @@ -238,6 +353,23 @@ async def fetch_async(self) -> UserBindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -256,6 +388,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -354,6 +487,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, binding_type: Union[ @@ -377,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -408,6 +602,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -417,6 +612,66 @@ async def list_async( ) ] + def list_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, binding_type: Union[ @@ -453,7 +708,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -491,7 +746,87 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserBindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserBindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserBindingPage: """ @@ -503,7 +838,7 @@ def get_page(self, target_url: str) -> UserBindingPage: :returns: Page of UserBindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserBindingPage: """ @@ -515,7 +850,7 @@ async def get_page_async(self, target_url: str) -> UserBindingPage: :returns: Page of UserBindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserBindingContext: """ diff --git a/twilio/rest/chat/v2/service/user/user_channel.py b/twilio/rest/chat/v2/service/user/user_channel.py index 9fab357368..1c4fe1c849 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -27,7 +28,7 @@ class UserChannelInstance(InstanceResource): class ChannelStatus(object): JOINED = "joined" INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + NOTPARTICIPATING = "notParticipating" class NotificationLevel(object): DEFAULT = "default" @@ -86,6 +87,7 @@ def __init__( "user_sid": user_sid, "channel_sid": channel_sid or self.channel_sid, } + self._context: Optional[UserChannelContext] = None @property @@ -139,6 +141,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserChannelInstance": """ Fetch the UserChannelInstance @@ -157,6 +193,24 @@ async def fetch_async(self) -> "UserChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -203,6 +257,52 @@ async def update_async( last_consumption_timestamp=last_consumption_timestamp, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +340,30 @@ def __init__( ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -253,6 +377,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -261,7 +418,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -276,32 +435,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> UserChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserChannelInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = self._fetch() return UserChannelInstance( self._version, payload, @@ -310,22 +490,47 @@ def fetch(self) -> UserChannelInstance: channel_sid=self._solution["channel_sid"], ) - async def fetch_async(self) -> UserChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserChannelInstance + Fetch the UserChannelInstance and return response metadata - :returns: The fetched UserChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = await self._fetch_async() return UserChannelInstance( self._version, payload, @@ -334,22 +539,36 @@ async def fetch_async(self) -> UserChannelInstance: channel_sid=self._solution["channel_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, notification_level: Union[ "UserChannelInstance.NotificationLevel", object ] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, last_consumption_timestamp: Union[datetime, object] = values.unset, - ) -> UserChannelInstance: + ) -> tuple: """ - Update the UserChannelInstance + Internal helper for update operation - :param notification_level: - :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. - :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). - - :returns: The updated UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -367,10 +586,32 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) return UserChannelInstance( self._version, payload, @@ -379,22 +620,50 @@ def update( channel_sid=self._solution["channel_sid"], ) - async def update_async( + def update_with_http_info( self, notification_level: Union[ "UserChannelInstance.NotificationLevel", object ] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, last_consumption_timestamp: Union[datetime, object] = values.unset, - ) -> UserChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserChannelInstance + Update the UserChannelInstance and return response metadata :param notification_level: :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). - :returns: The updated UserChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -412,10 +681,32 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) return UserChannelInstance( self._version, payload, @@ -424,6 +715,37 @@ async def update_async( channel_sid=self._solution["channel_sid"], ) + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance and return response metadata + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -442,6 +764,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -530,6 +853,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -549,6 +922,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -575,6 +949,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -583,6 +958,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -614,7 +1039,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -647,7 +1072,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserChannelPage: """ @@ -659,7 +1154,7 @@ def get_page(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserChannelPage: """ @@ -671,7 +1166,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def get(self, channel_sid: str) -> UserChannelContext: """ diff --git a/twilio/rest/chat/v3/channel.py b/twilio/rest/chat/v3/channel.py index 4682838fba..fa71c46897 100644 --- a/twilio/rest/chat/v3/channel.py +++ b/twilio/rest/chat/v3/channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid or self.service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -148,6 +150,52 @@ async def update_async( messaging_service_sid=messaging_service_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -177,22 +225,19 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) - def update( + def _update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object ] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Update the ChannelInstance + Internal helper for update operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param type: - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. - - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -216,10 +261,32 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) return ChannelInstance( self._version, payload, @@ -227,22 +294,49 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object ] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ChannelInstance + Update the ChannelInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param type: :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. - :returns: The updated ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -266,10 +360,32 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) return ChannelInstance( self._version, payload, @@ -277,6 +393,36 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/content/v1/content/__init__.py b/twilio/rest/content/v1/content/__init__.py index 60a5b05016..3e38e775a7 100644 --- a/twilio/rest/content/v1/content/__init__.py +++ b/twilio/rest/content/v1/content/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ class CallToActionAction(object): :ivar url: :ivar phone: :ivar code: + :ivar id: """ def __init__(self, payload: Dict[str, Any]): @@ -63,6 +65,7 @@ def __init__(self, payload: Dict[str, Any]): self.url: Optional[str] = payload.get("url") self.phone: Optional[str] = payload.get("phone") self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") def to_dict(self): return { @@ -71,6 +74,7 @@ def to_dict(self): "url": self.url, "phone": self.phone, "code": self.code, + "id": self.id, } class CardAction(object): @@ -81,6 +85,7 @@ class CardAction(object): :ivar phone: :ivar id: :ivar code: + :ivar webview_size: """ def __init__(self, payload: Dict[str, Any]): @@ -91,6 +96,9 @@ def __init__(self, payload: Dict[str, Any]): self.phone: Optional[str] = payload.get("phone") self.id: Optional[str] = payload.get("id") self.code: Optional[str] = payload.get("code") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) def to_dict(self): return { @@ -100,6 +108,7 @@ def to_dict(self): "phone": self.phone, "id": self.id, "code": self.code, + "webview_size": self.webview_size, } class CarouselAction(object): @@ -199,7 +208,30 @@ class ContentCreateRequest(object): def __init__(self, payload: Dict[str, Any]): self.friendly_name: Optional[str] = payload.get("friendly_name") - self.variables: Optional[dict[str, str]] = payload.get("variables") + self.variables: Optional[Dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class ContentUpdateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[Dict[str, str]] = payload.get("variables") self.language: Optional[str] = payload.get("language") self.types: Optional[ContentList.Types] = payload.get("types") @@ -470,6 +502,8 @@ class TwilioLocation(object): :ivar latitude: :ivar longitude: :ivar label: + :ivar id: + :ivar address: """ def __init__(self, payload: Dict[str, Any]): @@ -477,12 +511,16 @@ def __init__(self, payload: Dict[str, Any]): self.latitude: Optional[float] = payload.get("latitude") self.longitude: Optional[float] = payload.get("longitude") self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") def to_dict(self): return { "latitude": self.latitude, "longitude": self.longitude, "label": self.label, + "id": self.id, + "address": self.address, } class TwilioMedia(object): @@ -525,6 +563,26 @@ def to_dict(self): ), } + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": self.time_slots, + } + class TwilioText(object): """ :ivar body: @@ -551,107 +609,125 @@ class Types(object): :ivar twilio_catalog: :ivar twilio_carousel: :ivar twilio_flows: + :ivar twilio_schedule: :ivar whatsapp_card: :ivar whatsapp_authentication: + :ivar whatsapp_flows: """ def __init__(self, payload: Dict[str, Any]): self.twilio_text: Optional[ContentList.TwilioText] = payload.get( - "twilio_text" + "twilio/text" ) self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( - "twilio_media" + "twilio/media" ) self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( - "twilio_location" + "twilio/location" ) self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( - payload.get("twilio_list_picker") + payload.get("twilio/list-picker") ) self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( - payload.get("twilio_call_to_action") + payload.get("twilio/call-to-action") ) self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( - payload.get("twilio_quick_reply") + payload.get("twilio/quick-reply") ) self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( - "twilio_card" + "twilio/card" ) self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( - "twilio_catalog" + "twilio/catalog" ) self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( - "twilio_carousel" + "twilio/carousel" ) self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( - "twilio_flows" + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" ) self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( - "whatsapp_card" + "whatsapp/card" ) self.whatsapp_authentication: Optional[ ContentList.WhatsappAuthentication - ] = payload.get("whatsapp_authentication") + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) def to_dict(self): return { - "twilio_text": ( + "twilio/text": ( self.twilio_text.to_dict() if self.twilio_text is not None else None ), - "twilio_media": ( + "twilio/media": ( self.twilio_media.to_dict() if self.twilio_media is not None else None ), - "twilio_location": ( + "twilio/location": ( self.twilio_location.to_dict() if self.twilio_location is not None else None ), - "twilio_list_picker": ( + "twilio/list-picker": ( self.twilio_list_picker.to_dict() if self.twilio_list_picker is not None else None ), - "twilio_call_to_action": ( + "twilio/call-to-action": ( self.twilio_call_to_action.to_dict() if self.twilio_call_to_action is not None else None ), - "twilio_quick_reply": ( + "twilio/quick-reply": ( self.twilio_quick_reply.to_dict() if self.twilio_quick_reply is not None else None ), - "twilio_card": ( + "twilio/card": ( self.twilio_card.to_dict() if self.twilio_card is not None else None ), - "twilio_catalog": ( + "twilio/catalog": ( self.twilio_catalog.to_dict() if self.twilio_catalog is not None else None ), - "twilio_carousel": ( + "twilio/carousel": ( self.twilio_carousel.to_dict() if self.twilio_carousel is not None else None ), - "twilio_flows": ( + "twilio/flows": ( self.twilio_flows.to_dict() if self.twilio_flows is not None else None ), - "whatsapp_card": ( + "twilio/schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp/card": ( self.whatsapp_card.to_dict() if self.whatsapp_card is not None else None ), - "whatsapp_authentication": ( + "whatsapp/authentication": ( self.whatsapp_authentication.to_dict() if self.whatsapp_authentication is not None else None ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows is not None + else None + ), } class WhatsappAuthentication(object): @@ -716,6 +792,43 @@ def to_dict(self): ), } + class WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + class AuthenticationActionType(object): COPY_CODE = "COPY_CODE" @@ -725,6 +838,7 @@ class CallToActionActionType(object): COPY_CODE = "COPY_CODE" VOICE_CALL = "VOICE_CALL" VOICE_CALL_REQUEST = "VOICE_CALL_REQUEST" + REQUEST_CONTACT_INFO = "REQUEST_CONTACT_INFO" class CardActionType(object): URL = "URL" @@ -741,6 +855,12 @@ class CarouselActionType(object): class QuickReplyActionType(object): QUICK_REPLY = "QUICK_REPLY" + class WebviewSizeType(object): + TALL = "TALL" + FULL = "FULL" + HALF = "HALF" + NONE = "NONE" + """ :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. @@ -777,6 +897,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ContentContext] = None @property @@ -812,6 +933,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ContentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ContentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ContentInstance": """ Fetch the ContentInstance @@ -830,6 +969,78 @@ async def fetch_async(self) -> "ContentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update(self, content_update_request: ContentUpdateRequest) -> "ContentInstance": + """ + Update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + return self._proxy.update( + content_update_request=content_update_request, + ) + + async def update_async( + self, content_update_request: ContentUpdateRequest + ) -> "ContentInstance": + """ + Asynchronous coroutine to update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + return await self._proxy.update_async( + content_update_request=content_update_request, + ) + + def update_with_http_info( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Update the ContentInstance with HTTP info + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + content_update_request=content_update_request, + ) + + async def update_with_http_info_async( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ContentInstance with HTTP info + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + content_update_request=content_update_request, + ) + @property def approval_create(self) -> ApprovalCreateList: """ @@ -882,6 +1093,7 @@ class CallToActionAction(object): :ivar url: :ivar phone: :ivar code: + :ivar id: """ def __init__(self, payload: Dict[str, Any]): @@ -893,6 +1105,7 @@ def __init__(self, payload: Dict[str, Any]): self.url: Optional[str] = payload.get("url") self.phone: Optional[str] = payload.get("phone") self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") def to_dict(self): return { @@ -901,6 +1114,7 @@ def to_dict(self): "url": self.url, "phone": self.phone, "code": self.code, + "id": self.id, } class CardAction(object): @@ -911,6 +1125,7 @@ class CardAction(object): :ivar phone: :ivar id: :ivar code: + :ivar webview_size: """ def __init__(self, payload: Dict[str, Any]): @@ -921,6 +1136,9 @@ def __init__(self, payload: Dict[str, Any]): self.phone: Optional[str] = payload.get("phone") self.id: Optional[str] = payload.get("id") self.code: Optional[str] = payload.get("code") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) def to_dict(self): return { @@ -930,6 +1148,7 @@ def to_dict(self): "phone": self.phone, "id": self.id, "code": self.code, + "webview_size": self.webview_size, } class CarouselAction(object): @@ -1029,7 +1248,30 @@ class ContentCreateRequest(object): def __init__(self, payload: Dict[str, Any]): self.friendly_name: Optional[str] = payload.get("friendly_name") - self.variables: Optional[dict[str, str]] = payload.get("variables") + self.variables: Optional[Dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class ContentUpdateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[Dict[str, str]] = payload.get("variables") self.language: Optional[str] = payload.get("language") self.types: Optional[ContentList.Types] = payload.get("types") @@ -1300,6 +1542,8 @@ class TwilioLocation(object): :ivar latitude: :ivar longitude: :ivar label: + :ivar id: + :ivar address: """ def __init__(self, payload: Dict[str, Any]): @@ -1307,12 +1551,16 @@ def __init__(self, payload: Dict[str, Any]): self.latitude: Optional[float] = payload.get("latitude") self.longitude: Optional[float] = payload.get("longitude") self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") def to_dict(self): return { "latitude": self.latitude, "longitude": self.longitude, "label": self.label, + "id": self.id, + "address": self.address, } class TwilioMedia(object): @@ -1355,6 +1603,26 @@ def to_dict(self): ), } + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": self.time_slots, + } + class TwilioText(object): """ :ivar body: @@ -1381,107 +1649,125 @@ class Types(object): :ivar twilio_catalog: :ivar twilio_carousel: :ivar twilio_flows: + :ivar twilio_schedule: :ivar whatsapp_card: :ivar whatsapp_authentication: + :ivar whatsapp_flows: """ def __init__(self, payload: Dict[str, Any]): self.twilio_text: Optional[ContentList.TwilioText] = payload.get( - "twilio_text" + "twilio/text" ) self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( - "twilio_media" + "twilio/media" ) self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( - "twilio_location" + "twilio/location" ) self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( - payload.get("twilio_list_picker") + payload.get("twilio/list-picker") ) self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( - payload.get("twilio_call_to_action") + payload.get("twilio/call-to-action") ) self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( - payload.get("twilio_quick_reply") + payload.get("twilio/quick-reply") ) self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( - "twilio_card" + "twilio/card" ) self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( - "twilio_catalog" + "twilio/catalog" ) self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( - "twilio_carousel" + "twilio/carousel" ) self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( - "twilio_flows" + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" ) self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( - "whatsapp_card" + "whatsapp/card" ) self.whatsapp_authentication: Optional[ ContentList.WhatsappAuthentication - ] = payload.get("whatsapp_authentication") + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) def to_dict(self): return { - "twilio_text": ( + "twilio/text": ( self.twilio_text.to_dict() if self.twilio_text is not None else None ), - "twilio_media": ( + "twilio/media": ( self.twilio_media.to_dict() if self.twilio_media is not None else None ), - "twilio_location": ( + "twilio/location": ( self.twilio_location.to_dict() if self.twilio_location is not None else None ), - "twilio_list_picker": ( + "twilio/list-picker": ( self.twilio_list_picker.to_dict() if self.twilio_list_picker is not None else None ), - "twilio_call_to_action": ( + "twilio/call-to-action": ( self.twilio_call_to_action.to_dict() if self.twilio_call_to_action is not None else None ), - "twilio_quick_reply": ( + "twilio/quick-reply": ( self.twilio_quick_reply.to_dict() if self.twilio_quick_reply is not None else None ), - "twilio_card": ( + "twilio/card": ( self.twilio_card.to_dict() if self.twilio_card is not None else None ), - "twilio_catalog": ( + "twilio/catalog": ( self.twilio_catalog.to_dict() if self.twilio_catalog is not None else None ), - "twilio_carousel": ( + "twilio/carousel": ( self.twilio_carousel.to_dict() if self.twilio_carousel is not None else None ), - "twilio_flows": ( + "twilio/flows": ( self.twilio_flows.to_dict() if self.twilio_flows is not None else None ), - "whatsapp_card": ( + "twilio/schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp/card": ( self.whatsapp_card.to_dict() if self.whatsapp_card is not None else None ), - "whatsapp_authentication": ( + "whatsapp/authentication": ( self.whatsapp_authentication.to_dict() if self.whatsapp_authentication is not None else None ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows is not None + else None + ), } class WhatsappAuthentication(object): @@ -1546,12 +1832,49 @@ def to_dict(self): ), } + class WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + def __init__(self, version: Version, sid: str): """ Initialize the ContentContext :param version: Version that contains the resource - :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Content resource to update. """ super().__init__(version) @@ -1564,6 +1887,20 @@ def __init__(self, version: Version, sid: str): self._approval_create: Optional[ApprovalCreateList] = None self._approval_fetch: Optional[ApprovalFetchList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ContentInstance @@ -1571,10 +1908,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ContentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -1583,64 +1942,216 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ContentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ContentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ContentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ContentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ContentInstance: + """ + Fetch the ContentInstance + + :returns: The fetched ContentInstance + """ + payload, _, _ = self._fetch() return ContentInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ContentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ContentInstance + Fetch the ContentInstance and return response metadata - :returns: The fetched ContentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ContentInstance: + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + payload, _, _ = await self._fetch_async() return ContentInstance( self._version, payload, sid=self._solution["sid"], ) - @property - def approval_create(self) -> ApprovalCreateList: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Access the approval_create + Asynchronous coroutine to fetch the ContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - if self._approval_create is None: - self._approval_create = ApprovalCreateList( - self._version, - self._solution["sid"], + payload, status_code, headers = await self._fetch_async() + instance = ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, content_update_request: ContentUpdateRequest) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update(self, content_update_request: ContentUpdateRequest) -> ContentInstance: + """ + Update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + payload, _, _ = self._update(content_update_request=content_update_request) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Update the ContentInstance and return response metadata + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + content_update_request=content_update_request + ) + instance = ContentInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, content_update_request: ContentUpdateRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, content_update_request: ContentUpdateRequest + ) -> ContentInstance: + """ + Asynchronous coroutine to update the ContentInstance + + :param content_update_request: + + :returns: The updated ContentInstance + """ + payload, _, _ = await self._update_async( + content_update_request=content_update_request + ) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ContentInstance and return response metadata + + :param content_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + content_update_request=content_update_request + ) + instance = ContentInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def approval_create(self) -> ApprovalCreateList: + """ + Access the approval_create + """ + if self._approval_create is None: + self._approval_create = ApprovalCreateList( + self._version, + self._solution["sid"], ) return self._approval_create @@ -1674,6 +2185,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: :param payload: Payload response from the API """ + return ContentInstance(self._version, payload) def __repr__(self) -> str: @@ -1713,6 +2225,7 @@ class CallToActionAction(object): :ivar url: :ivar phone: :ivar code: + :ivar id: """ def __init__(self, payload: Dict[str, Any]): @@ -1724,6 +2237,7 @@ def __init__(self, payload: Dict[str, Any]): self.url: Optional[str] = payload.get("url") self.phone: Optional[str] = payload.get("phone") self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") def to_dict(self): return { @@ -1732,6 +2246,7 @@ def to_dict(self): "url": self.url, "phone": self.phone, "code": self.code, + "id": self.id, } class CardAction(object): @@ -1742,6 +2257,7 @@ class CardAction(object): :ivar phone: :ivar id: :ivar code: + :ivar webview_size: """ def __init__(self, payload: Dict[str, Any]): @@ -1752,6 +2268,9 @@ def __init__(self, payload: Dict[str, Any]): self.phone: Optional[str] = payload.get("phone") self.id: Optional[str] = payload.get("id") self.code: Optional[str] = payload.get("code") + self.webview_size: Optional["ContentInstance.WebviewSizeType"] = ( + payload.get("webview_size") + ) def to_dict(self): return { @@ -1761,6 +2280,7 @@ def to_dict(self): "phone": self.phone, "id": self.id, "code": self.code, + "webview_size": self.webview_size, } class CarouselAction(object): @@ -1860,7 +2380,30 @@ class ContentCreateRequest(object): def __init__(self, payload: Dict[str, Any]): self.friendly_name: Optional[str] = payload.get("friendly_name") - self.variables: Optional[dict[str, str]] = payload.get("variables") + self.variables: Optional[Dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class ContentUpdateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[Dict[str, str]] = payload.get("variables") self.language: Optional[str] = payload.get("language") self.types: Optional[ContentList.Types] = payload.get("types") @@ -2131,6 +2674,8 @@ class TwilioLocation(object): :ivar latitude: :ivar longitude: :ivar label: + :ivar id: + :ivar address: """ def __init__(self, payload: Dict[str, Any]): @@ -2138,12 +2683,16 @@ def __init__(self, payload: Dict[str, Any]): self.latitude: Optional[float] = payload.get("latitude") self.longitude: Optional[float] = payload.get("longitude") self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") def to_dict(self): return { "latitude": self.latitude, "longitude": self.longitude, "label": self.label, + "id": self.id, + "address": self.address, } class TwilioMedia(object): @@ -2186,6 +2735,26 @@ def to_dict(self): ), } + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("timeSlots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "timeSlots": self.time_slots, + } + class TwilioText(object): """ :ivar body: @@ -2212,107 +2781,125 @@ class Types(object): :ivar twilio_catalog: :ivar twilio_carousel: :ivar twilio_flows: + :ivar twilio_schedule: :ivar whatsapp_card: :ivar whatsapp_authentication: + :ivar whatsapp_flows: """ def __init__(self, payload: Dict[str, Any]): self.twilio_text: Optional[ContentList.TwilioText] = payload.get( - "twilio_text" + "twilio/text" ) self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( - "twilio_media" + "twilio/media" ) self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( - "twilio_location" + "twilio/location" ) self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( - payload.get("twilio_list_picker") + payload.get("twilio/list-picker") ) self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( - payload.get("twilio_call_to_action") + payload.get("twilio/call-to-action") ) self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( - payload.get("twilio_quick_reply") + payload.get("twilio/quick-reply") ) self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( - "twilio_card" + "twilio/card" ) self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( - "twilio_catalog" + "twilio/catalog" ) self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( - "twilio_carousel" + "twilio/carousel" ) self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( - "twilio_flows" + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" ) self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( - "whatsapp_card" + "whatsapp/card" ) self.whatsapp_authentication: Optional[ ContentList.WhatsappAuthentication - ] = payload.get("whatsapp_authentication") + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) def to_dict(self): return { - "twilio_text": ( + "twilio/text": ( self.twilio_text.to_dict() if self.twilio_text is not None else None ), - "twilio_media": ( + "twilio/media": ( self.twilio_media.to_dict() if self.twilio_media is not None else None ), - "twilio_location": ( + "twilio/location": ( self.twilio_location.to_dict() if self.twilio_location is not None else None ), - "twilio_list_picker": ( + "twilio/list-picker": ( self.twilio_list_picker.to_dict() if self.twilio_list_picker is not None else None ), - "twilio_call_to_action": ( + "twilio/call-to-action": ( self.twilio_call_to_action.to_dict() if self.twilio_call_to_action is not None else None ), - "twilio_quick_reply": ( + "twilio/quick-reply": ( self.twilio_quick_reply.to_dict() if self.twilio_quick_reply is not None else None ), - "twilio_card": ( + "twilio/card": ( self.twilio_card.to_dict() if self.twilio_card is not None else None ), - "twilio_catalog": ( + "twilio/catalog": ( self.twilio_catalog.to_dict() if self.twilio_catalog is not None else None ), - "twilio_carousel": ( + "twilio/carousel": ( self.twilio_carousel.to_dict() if self.twilio_carousel is not None else None ), - "twilio_flows": ( + "twilio/flows": ( self.twilio_flows.to_dict() if self.twilio_flows is not None else None ), - "whatsapp_card": ( + "twilio/schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp/card": ( self.whatsapp_card.to_dict() if self.whatsapp_card is not None else None ), - "whatsapp_authentication": ( + "whatsapp/authentication": ( self.whatsapp_authentication.to_dict() if self.whatsapp_authentication is not None else None ), + "whatsapp/flows": ( + self.whatsapp_flows.to_dict() + if self.whatsapp_flows is not None + else None + ), } class WhatsappAuthentication(object): @@ -2377,6 +2964,43 @@ def to_dict(self): ), } + class WhatsappFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar flow_id: + :ivar flow_token: + :ivar flow_first_page_id: + :ivar is_flow_first_page_endpoint: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.flow_id: Optional[str] = payload.get("flow_id") + self.flow_token: Optional[str] = payload.get("flow_token") + self.flow_first_page_id: Optional[str] = payload.get("flow_first_page_id") + self.is_flow_first_page_endpoint: Optional[bool] = payload.get( + "is_flow_first_page_endpoint" + ) + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "flow_id": self.flow_id, + "flow_token": self.flow_token, + "flow_first_page_id": self.flow_first_page_id, + "is_flow_first_page_endpoint": self.is_flow_first_page_endpoint, + } + def __init__(self, version: Version): """ Initialize the ContentList @@ -2388,13 +3012,12 @@ def __init__(self, version: Version): self._uri = "/Content" - def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: + def _create(self, content_create_request: ContentCreateRequest) -> tuple: """ - Create the ContentInstance + Internal helper for create operation - :param content_create_request: - - :returns: The created ContentInstance + Returns: + tuple: (payload, status_code, headers) """ data = content_create_request.to_dict() @@ -2404,21 +3027,45 @@ def create(self, content_create_request: ContentCreateRequest) -> ContentInstanc headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: + """ + Create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + payload, _, _ = self._create(content_create_request=content_create_request) return ContentInstance(self._version, payload) - async def create_async( + def create_with_http_info( self, content_create_request: ContentCreateRequest - ) -> ContentInstance: + ) -> ApiResponse: """ - Asynchronously create the ContentInstance + Create the ContentInstance and return response metadata :param content_create_request: - :returns: The created ContentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content_create_request: ContentCreateRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = content_create_request.to_dict() @@ -2428,12 +3075,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, content_create_request: ContentCreateRequest + ) -> ContentInstance: + """ + Asynchronously create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + payload, _, _ = await self._create_async( + content_create_request=content_create_request + ) return ContentInstance(self._version, payload) + async def create_with_http_info_async( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: + """ + Asynchronously create the ContentInstance and return response metadata + + :param content_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -2484,6 +3160,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -2503,6 +3229,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -2529,6 +3256,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -2537,6 +3265,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -2603,6 +3381,76 @@ async def page_async( ) return ContentPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentPage: """ Retrieve a specific page of ContentInstance records from the API. @@ -2631,7 +3479,7 @@ def get(self, sid: str) -> ContentContext: """ Constructs a ContentContext - :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Content resource to update. """ return ContentContext(self._version, sid=sid) @@ -2639,7 +3487,7 @@ def __call__(self, sid: str) -> ContentContext: """ Constructs a ContentContext - :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Content resource to update. """ return ContentContext(self._version, sid=sid) diff --git a/twilio/rest/content/v1/content/approval_create.py b/twilio/rest/content/v1/content/approval_create.py index 9f34064e35..2487ec6090 100644 --- a/twilio/rest/content/v1/content/approval_create.py +++ b/twilio/rest/content/v1/content/approval_create.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -111,15 +112,12 @@ def __init__(self, version: Version, content_sid: str): **self._solution ) - def create( - self, content_approval_request: ContentApprovalRequest - ) -> ApprovalCreateInstance: + def _create(self, content_approval_request: ContentApprovalRequest) -> tuple: """ - Create the ApprovalCreateInstance + Internal helper for create operation - :param content_approval_request: - - :returns: The created ApprovalCreateInstance + Returns: + tuple: (payload, status_code, headers) """ data = content_approval_request.to_dict() @@ -129,23 +127,51 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + payload, _, _ = self._create(content_approval_request=content_approval_request) return ApprovalCreateInstance( self._version, payload, content_sid=self._solution["content_sid"] ) - async def create_async( + def create_with_http_info( self, content_approval_request: ContentApprovalRequest - ) -> ApprovalCreateInstance: + ) -> ApiResponse: """ - Asynchronously create the ApprovalCreateInstance + Create the ApprovalCreateInstance and return response metadata :param content_approval_request: - :returns: The created ApprovalCreateInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content_approval_request=content_approval_request + ) + instance = ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content_approval_request: ContentApprovalRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = content_approval_request.to_dict() @@ -155,14 +181,45 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Asynchronously create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + payload, _, _ = await self._create_async( + content_approval_request=content_approval_request + ) return ApprovalCreateInstance( self._version, payload, content_sid=self._solution["content_sid"] ) + async def create_with_http_info_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApiResponse: + """ + Asynchronously create the ApprovalCreateInstance and return response metadata + + :param content_approval_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content_approval_request=content_approval_request + ) + instance = ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/content/v1/content/approval_fetch.py b/twilio/rest/content/v1/content/approval_fetch.py index d3d00e5058..47b00a89ec 100644 --- a/twilio/rest/content/v1/content/approval_fetch.py +++ b/twilio/rest/content/v1/content/approval_fetch.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -39,6 +40,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[ApprovalFetchContext] = None @property @@ -74,6 +76,24 @@ async def fetch_async(self) -> "ApprovalFetchInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApprovalFetchInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -101,48 +121,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Content/{sid}/ApprovalRequests".format(**self._solution) - def fetch(self) -> ApprovalFetchInstance: + def _fetch(self) -> tuple: """ - Fetch the ApprovalFetchInstance + Internal helper for fetch operation - - :returns: The fetched ApprovalFetchInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ApprovalFetchInstance: + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + payload, _, _ = self._fetch() return ApprovalFetchInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ApprovalFetchInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ApprovalFetchInstance + Fetch the ApprovalFetchInstance and return response metadata - :returns: The fetched ApprovalFetchInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ApprovalFetchInstance: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + payload, _, _ = await self._fetch_async() return ApprovalFetchInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/content/v1/content_and_approvals.py b/twilio/rest/content/v1/content_and_approvals.py index c2a210665d..73c009e1be 100644 --- a/twilio/rest/content/v1/content_and_approvals.py +++ b/twilio/rest/content/v1/content_and_approvals.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: :param payload: Payload response from the API """ + return ContentAndApprovalsInstance(self._version, payload) def __repr__(self) -> str: @@ -146,6 +148,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -165,6 +217,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -191,6 +244,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -199,6 +253,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -265,6 +369,76 @@ async def page_async( ) return ContentAndApprovalsPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentAndApprovalsPage: """ Retrieve a specific page of ContentAndApprovalsInstance records from the API. diff --git a/twilio/rest/content/v1/legacy_content.py b/twilio/rest/content/v1/legacy_content.py index d32778e748..a600809360 100644 --- a/twilio/rest/content/v1/legacy_content.py +++ b/twilio/rest/content/v1/legacy_content.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LegacyContentInstance: :param payload: Payload response from the API """ + return LegacyContentInstance(self._version, payload) def __repr__(self) -> str: @@ -148,6 +150,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -167,6 +219,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -193,6 +246,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -201,6 +255,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -267,6 +371,76 @@ async def page_async( ) return LegacyContentPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LegacyContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LegacyContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LegacyContentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LegacyContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> LegacyContentPage: """ Retrieve a specific page of LegacyContentInstance records from the API. diff --git a/twilio/rest/content/v2/content.py b/twilio/rest/content/v2/content.py index c2e2db7d8c..2584c2fd5d 100644 --- a/twilio/rest/content/v2/content.py +++ b/twilio/rest/content/v2/content.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: :param payload: Payload response from the API """ + return ContentInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +206,112 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sort_by_date: Union[str, object] = values.unset, @@ -241,6 +349,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sort_by_date=sort_by_date, @@ -294,6 +403,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +421,110 @@ async def list_async( ) ] + def list_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sort_by_date: Union[str, object] = values.unset, @@ -431,6 +645,130 @@ async def page_async( ) return ContentPage(self._version, response) + def page_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentPage: """ Retrieve a specific page of ContentInstance records from the API. diff --git a/twilio/rest/content/v2/content_and_approvals.py b/twilio/rest/content/v2/content_and_approvals.py index 823bcfe083..e383867e93 100644 --- a/twilio/rest/content/v2/content_and_approvals.py +++ b/twilio/rest/content/v2/content_and_approvals.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: :param payload: Payload response from the API """ + return ContentAndApprovalsInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +206,112 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sort_by_date: Union[str, object] = values.unset, @@ -241,6 +349,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sort_by_date=sort_by_date, @@ -294,6 +403,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +421,110 @@ async def list_async( ) ] + def list_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sort_by_date: Union[str, object] = values.unset, @@ -431,6 +645,130 @@ async def page_async( ) return ContentAndApprovalsPage(self._version, response) + def page_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentAndApprovalsPage: """ Retrieve a specific page of ContentAndApprovalsInstance records from the API. diff --git a/twilio/rest/conversations/ConversationsBase.py b/twilio/rest/conversations/ConversationsBase.py index 8904308365..0a34545412 100644 --- a/twilio/rest/conversations/ConversationsBase.py +++ b/twilio/rest/conversations/ConversationsBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.conversations.v1 import V1 +from twilio.rest.conversations.v2 import V2 class ConversationsBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://conversations.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: @@ -36,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Conversations + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/address_configuration.py b/twilio/rest/conversations/v1/address_configuration.py index 4ebfa47fc2..3c0864ec2f 100644 --- a/twilio/rest/conversations/v1/address_configuration.py +++ b/twilio/rest/conversations/v1/address_configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,8 +31,8 @@ class AutoCreationType(object): DEFAULT = "default" class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Type(object): SMS = "sms" @@ -40,6 +41,8 @@ class Type(object): GBM = "gbm" EMAIL = "email" RCS = "rcs" + APPLE = "apple" + CHAT = "chat" """ :ivar sid: A 34 character string that uniquely identifies this resource. @@ -77,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AddressConfigurationContext] = None @property @@ -112,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AddressConfigurationInstance": """ Fetch the AddressConfigurationInstance @@ -130,6 +152,24 @@ async def fetch_async(self) -> "AddressConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -216,6 +256,92 @@ async def update_async( auto_creation_studio_retry_count=auto_creation_studio_retry_count, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the AddressConfigurationInstance with HTTP info + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressConfigurationInstance with HTTP info + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -245,6 +371,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Configuration/Addresses/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AddressConfigurationInstance @@ -252,10 +392,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -264,56 +426,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AddressConfigurationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AddressConfigurationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AddressConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressConfigurationInstance: + """ + Fetch the AddressConfigurationInstance + + :returns: The fetched AddressConfigurationInstance + """ + payload, _, _ = self._fetch() return AddressConfigurationInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AddressConfigurationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AddressConfigurationInstance + Fetch the AddressConfigurationInstance and return response metadata - :returns: The fetched AddressConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return AddressConfigurationInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, auto_creation_enabled: Union[bool, object] = values.unset, @@ -328,21 +544,12 @@ def update( auto_creation_webhook_filters: Union[List[str], object] = values.unset, auto_creation_studio_flow_sid: Union[str, object] = values.unset, auto_creation_studio_retry_count: Union[int, object] = values.unset, - ) -> AddressConfigurationInstance: + ) -> tuple: """ - Update the AddressConfigurationInstance - - :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. - :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address - :param auto_creation_type: - :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. - :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. - :param auto_creation_webhook_method: - :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` - :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. - :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + Internal helper for update operation - :returns: The updated AddressConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,15 +575,57 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) return AddressConfigurationInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, auto_creation_enabled: Union[bool, object] = values.unset, @@ -391,9 +640,9 @@ async def update_async( auto_creation_webhook_filters: Union[List[str], object] = values.unset, auto_creation_studio_flow_sid: Union[str, object] = values.unset, auto_creation_studio_retry_count: Union[int, object] = values.unset, - ) -> AddressConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AddressConfigurationInstance + Update the AddressConfigurationInstance and return response metadata :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address @@ -405,7 +654,45 @@ async def update_async( :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request - :returns: The updated AddressConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -431,16 +718,105 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return AddressConfigurationInstance( - self._version, payload, sid=self._solution["sid"] - ) - - def __repr__(self) -> str: - """ + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressConfigurationInstance and return response metadata + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ Provide a friendly representation :returns: Machine friendly representation @@ -459,6 +835,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: :param payload: Payload response from the API """ + return AddressConfigurationInstance(self._version, payload) def __repr__(self) -> str: @@ -483,7 +860,7 @@ def __init__(self, version: Version): self._uri = "/Configuration/Addresses" - def create( + def _create( self, type: "AddressConfigurationInstance.Type", address: str, @@ -501,24 +878,12 @@ def create( auto_creation_studio_flow_sid: Union[str, object] = values.unset, auto_creation_studio_retry_count: Union[int, object] = values.unset, address_country: Union[str, object] = values.unset, - ) -> AddressConfigurationInstance: + ) -> tuple: """ - Create the AddressConfigurationInstance - - :param type: - :param address: The unique address to be configured. The address can be a whatsapp address or phone number - :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. - :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address - :param auto_creation_type: - :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. - :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. - :param auto_creation_webhook_method: - :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` - :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. - :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request - :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + Internal helper for create operation - :returns: The created AddressConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -547,13 +912,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AddressConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, type: "AddressConfigurationInstance.Type", address: str, @@ -573,7 +936,7 @@ async def create_async( address_country: Union[str, object] = values.unset, ) -> AddressConfigurationInstance: """ - Asynchronously create the AddressConfigurationInstance + Create the AddressConfigurationInstance :param type: :param address: The unique address to be configured. The address can be a whatsapp address or phone number @@ -590,6 +953,101 @@ async def create_async( :returns: The created AddressConfigurationInstance """ + payload, _, _ = self._create( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + return AddressConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AddressConfigurationInstance and return response metadata + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -617,12 +1075,117 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronously create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + payload, _, _ = await self._create_async( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) return AddressConfigurationInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AddressConfigurationInstance and return response metadata + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[str, object] = values.unset, @@ -677,6 +1240,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AddressConfigurationInstance and returns headers from first page + + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AddressConfigurationInstance and returns headers from first page + + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, type: Union[str, object] = values.unset, @@ -698,6 +1317,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -727,6 +1347,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -736,6 +1357,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AddressConfigurationInstance and returns headers from first page + + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AddressConfigurationInstance and returns headers from first page + + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, type: Union[str, object] = values.unset, @@ -808,6 +1485,82 @@ async def page_async( ) return AddressConfigurationPage(self._version, response) + def page_with_http_info( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddressConfigurationPage, status code, and headers + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AddressConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AddressConfigurationPage, status code, and headers + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AddressConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AddressConfigurationPage: """ Retrieve a specific page of AddressConfigurationInstance records from the API. diff --git a/twilio/rest/conversations/v1/configuration/__init__.py b/twilio/rest/conversations/v1/configuration/__init__.py index 584082353f..ec2a73badd 100644 --- a/twilio/rest/conversations/v1/configuration/__init__.py +++ b/twilio/rest/conversations/v1/configuration/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,24 @@ async def fetch_async(self) -> "ConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_chat_service_sid: Union[str, object] = values.unset, @@ -132,6 +151,54 @@ async def update_async( default_closed_timer=default_closed_timer, ) + def update_with_http_info( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + async def update_with_http_info_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,62 +221,104 @@ def __init__(self, version: Version): self._uri = "/Configuration" - def fetch(self) -> ConfigurationInstance: + def _fetch(self) -> tuple: """ - Fetch the ConfigurationInstance + Internal helper for fetch operation - - :returns: The fetched ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() return ConfigurationInstance( self._version, payload, ) - async def fetch_async(self) -> ConfigurationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConfigurationInstance + Fetch the ConfigurationInstance and return response metadata - :returns: The fetched ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return ConfigurationInstance( self._version, payload, ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, default_chat_service_sid: Union[str, object] = values.unset, default_messaging_service_sid: Union[str, object] = values.unset, default_inactive_timer: Union[str, object] = values.unset, default_closed_timer: Union[str, object] = values.unset, - ) -> ConfigurationInstance: + ) -> tuple: """ - Update the ConfigurationInstance - - :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. - :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. - :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + Internal helper for update operation - :returns: The updated ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -226,13 +335,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConfigurationInstance(self._version, payload) - - async def update_async( + def update( self, default_chat_service_sid: Union[str, object] = values.unset, default_messaging_service_sid: Union[str, object] = values.unset, @@ -240,7 +347,7 @@ async def update_async( default_closed_timer: Union[str, object] = values.unset, ) -> ConfigurationInstance: """ - Asynchronous coroutine to update the ConfigurationInstance + Update the ConfigurationInstance :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. @@ -249,6 +356,53 @@ async def update_async( :returns: The updated ConfigurationInstance """ + payload, _, _ = self._update( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + return ConfigurationInstance(self._version, payload) + + def update_with_http_info( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -264,12 +418,61 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) return ConfigurationInstance(self._version, payload) + async def update_with_http_info_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/configuration/webhook.py b/twilio/rest/conversations/v1/configuration/webhook.py index f471c879ab..d286bba936 100644 --- a/twilio/rest/conversations/v1/configuration/webhook.py +++ b/twilio/rest/conversations/v1/configuration/webhook.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, method: Union[str, object] = values.unset, @@ -139,6 +158,60 @@ async def update_async( target=target, ) + def update_with_http_info( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + async def update_with_http_info_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -161,64 +234,105 @@ def __init__(self, version: Version): self._uri = "/Configuration/Webhooks" - def fetch(self) -> WebhookInstance: + def _fetch(self) -> tuple: """ - Fetch the WebhookInstance - + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, method: Union[str, object] = values.unset, filters: Union[List[str], object] = values.unset, pre_webhook_url: Union[str, object] = values.unset, post_webhook_url: Union[str, object] = values.unset, target: Union["WebhookInstance.Target", object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance - - :param method: The HTTP method to be used when sending a webhook request. - :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` - :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. - :param post_webhook_url: The absolute url the post-event webhook request should be sent to. - :param target: + Internal helper for update operation - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -236,13 +350,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WebhookInstance(self._version, payload) - - async def update_async( + def update( self, method: Union[str, object] = values.unset, filters: Union[List[str], object] = values.unset, @@ -251,7 +363,7 @@ async def update_async( target: Union["WebhookInstance.Target", object] = values.unset, ) -> WebhookInstance: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance :param method: The HTTP method to be used when sending a webhook request. :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` @@ -261,6 +373,58 @@ async def update_async( :returns: The updated WebhookInstance """ + payload, _, _ = self._update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + return WebhookInstance(self._version, payload) + + def update_with_http_info( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance and return response metadata + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -277,12 +441,67 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) return WebhookInstance(self._version, payload) + async def update_with_http_info_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/conversation/__init__.py b/twilio/rest/conversations/v1/conversation/__init__.py index d1f08cc2d8..808ab297e8 100644 --- a/twilio/rest/conversations/v1/conversation/__init__.py +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class ConversationInstance(InstanceResource): class State(object): + INITIALIZING = "initializing" INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" @@ -80,6 +82,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ConversationContext] = None @property @@ -131,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ConversationInstance": """ Fetch the ConversationInstance @@ -149,6 +186,24 @@ async def fetch_async(self) -> "ConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -249,6 +304,106 @@ async def update_async( bindings_email_name=bindings_email_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + @property def messages(self) -> MessageList: """ @@ -301,6 +456,30 @@ def __init__(self, version: Version, sid: str): self._participants: Optional[ParticipantList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -314,6 +493,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -322,7 +534,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -337,61 +551,120 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ConversationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ConversationInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() return ConversationInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ConversationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConversationInstance + Fetch the ConversationInstance and return response metadata - :returns: The fetched ConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() return ConversationInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -407,24 +680,12 @@ def update( unique_name: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> tuple: """ - Update the ConversationInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + Internal helper for update operation - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -457,13 +718,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConversationInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -481,7 +740,7 @@ async def update_async( bindings_email_name: Union[str, object] = values.unset, ) -> ConversationInstance: """ - Asynchronous coroutine to update the ConversationInstance + Update the ConversationInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -498,8 +757,101 @@ async def update_async( :returns: The updated ConversationInstance """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) - data = values.of( + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( { "FriendlyName": friendly_name, "DateCreated": serialize.iso8601_datetime(date_created), @@ -529,12 +881,115 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def messages(self) -> MessageList: """ @@ -589,6 +1044,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: :param payload: Payload response from the API """ + return ConversationInstance(self._version, payload) def __repr__(self) -> str: @@ -613,6 +1069,60 @@ def __init__(self, version: Version): self._uri = "/Conversations" + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, x_twilio_webhook_enabled: Union[ @@ -648,6 +1158,97 @@ def create( :returns: The created ConversationInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance(self._version, payload) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -673,15 +1274,64 @@ def create( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + :returns: The created ConversationInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, ) - return ConversationInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -697,9 +1347,9 @@ async def create_async( timers_closed: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> ApiResponse: """ - Asynchronously create the ConversationInstance + Asynchronously create the ConversationInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -714,40 +1364,24 @@ async def create_async( :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :returns: The created ConversationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "MessagingServiceSid": messaging_service_sid, - "Attributes": attributes, - "State": state, - "Timers.Inactive": timers_inactive, - "Timers.Closed": timers_closed, - "Bindings.Email.Address": bindings_email_address, - "Bindings.Email.Name": bindings_email_name, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - "Content-Type": "application/x-www-form-urlencoded", - } - ) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, ) - - return ConversationInstance(self._version, payload) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -821,6 +1455,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, start_date: Union[str, object] = values.unset, @@ -846,6 +1550,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -881,6 +1586,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -892,6 +1598,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, start_date: Union[str, object] = values.unset, @@ -976,6 +1750,94 @@ async def page_async( ) return ConversationPage(self._version, response) + def page_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ConversationPage: """ Retrieve a specific page of ConversationInstance records from the API. diff --git a/twilio/rest/conversations/v1/conversation/message/__init__.py b/twilio/rest/conversations/v1/conversation/message/__init__.py index 04e7fdf252..947d8f466d 100644 --- a/twilio/rest/conversations/v1/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -138,6 +140,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -156,6 +192,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -174,8 +228,8 @@ def update( :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. @@ -209,8 +263,8 @@ async def update_async( :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. @@ -226,6 +280,76 @@ async def update_async( subject=subject, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + @property def delivery_receipts(self) -> DeliveryReceiptList: """ @@ -266,6 +390,30 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): self._delivery_receipts: Optional[DeliveryReceiptList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -279,6 +427,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -287,7 +468,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -302,32 +485,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -335,22 +539,46 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -358,7 +586,23 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -369,19 +613,12 @@ def update( date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param subject: The subject of the message, can be up to 256 characters long. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -409,18 +646,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MessageInstance( - self._version, - payload, - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -433,48 +663,27 @@ async def update_async( subject: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. :returns: The updated MessageInstance """ - - data = values.of( - { - "Author": author, - "Body": body, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "Subject": subject, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, ) - return MessageInstance( self._version, payload, @@ -482,10 +691,183 @@ async def update_async( sid=self._solution["sid"], ) - @property - def delivery_receipts(self) -> DeliveryReceiptList: - """ - Access the delivery_receipts + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts """ if self._delivery_receipts is None: self._delivery_receipts = DeliveryReceiptList( @@ -513,6 +895,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -546,7 +929,7 @@ def __init__(self, version: Version, conversation_sid: str): **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -560,22 +943,12 @@ def create( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param media_sid: The Media SID to be attached to the new Message. - :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. - :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. - :param subject: The subject of the message, can be up to 256 characters long. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -602,15 +975,58 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) return MessageInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -624,22 +1040,60 @@ async def create_async( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param media_sid: The Media SID to be attached to the new Message. :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. :param subject: The subject of the message, can be up to 256 characters long. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -666,14 +1120,105 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) return MessageInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -728,6 +1273,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -749,6 +1350,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -778,6 +1380,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -787,6 +1390,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -821,7 +1480,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -857,7 +1516,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -869,7 +1604,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -881,7 +1616,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py index 2ed297e059..ffebce0840 100644 --- a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[DeliveryReceiptContext] = None @property @@ -115,6 +117,24 @@ async def fetch_async(self) -> "DeliveryReceiptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,20 +170,30 @@ def __init__( **self._solution ) - def fetch(self) -> DeliveryReceiptInstance: + def _fetch(self) -> tuple: """ - Fetch the DeliveryReceiptInstance - + Internal helper for fetch operation - :returns: The fetched DeliveryReceiptInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = self._fetch() return DeliveryReceiptInstance( self._version, payload, @@ -172,22 +202,47 @@ def fetch(self) -> DeliveryReceiptInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> DeliveryReceiptInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DeliveryReceiptInstance + Fetch the DeliveryReceiptInstance and return response metadata - :returns: The fetched DeliveryReceiptInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = await self._fetch_async() return DeliveryReceiptInstance( self._version, payload, @@ -196,6 +251,23 @@ async def fetch_async(self) -> DeliveryReceiptInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -214,6 +286,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -304,6 +377,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -323,6 +446,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -349,6 +473,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -357,6 +482,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -388,7 +563,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) async def page_async( self, @@ -421,7 +596,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DeliveryReceiptPage: """ @@ -433,7 +678,7 @@ def get_page(self, target_url: str) -> DeliveryReceiptPage: :returns: Page of DeliveryReceiptInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: """ @@ -445,7 +690,7 @@ async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: :returns: Page of DeliveryReceiptInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DeliveryReceiptContext: """ diff --git a/twilio/rest/conversations/v1/conversation/participant.py b/twilio/rest/conversations/v1/conversation/participant.py index deb652641a..0600512c97 100644 --- a/twilio/rest/conversations/v1/conversation/participant.py +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -129,6 +131,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -147,6 +183,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -235,6 +289,94 @@ async def update_async( last_read_timestamp=last_read_timestamp, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -266,6 +408,30 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): **self._solution ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -279,6 +445,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -287,7 +486,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -302,32 +503,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ParticipantInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ParticipantInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -335,22 +557,46 @@ def fetch(self) -> ParticipantInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -358,7 +604,23 @@ async def fetch_async(self) -> ParticipantInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -372,22 +634,12 @@ def update( identity: Union[str, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, last_read_timestamp: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Update the ParticipantInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. - :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. - :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. - :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + Internal helper for update operation - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,18 +670,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ParticipantInstance( - self._version, - payload, - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -445,7 +690,7 @@ async def update_async( last_read_timestamp: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronous coroutine to update the ParticipantInstance + Update the ParticipantInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param date_created: The date that this resource was created. @@ -460,12 +705,103 @@ async def update_async( :returns: The updated ParticipantInstance """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) - data = values.of( - { - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, "RoleSid": role_sid, "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, @@ -489,10 +825,53 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) return ParticipantInstance( self._version, payload, @@ -500,6 +879,57 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -518,6 +948,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -551,7 +982,7 @@ def __init__(self, version: Version, conversation_sid: str): **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -564,21 +995,12 @@ def create( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. - :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). - :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. - :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + Internal helper for create operation - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -604,15 +1026,55 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) return ParticipantInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -625,9 +1087,9 @@ async def create_async( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. @@ -639,7 +1101,43 @@ async def create_async( :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -665,14 +1163,99 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) return ParticipantInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -723,6 +1306,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -742,6 +1375,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -768,6 +1402,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -776,6 +1411,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -807,7 +1492,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -840,7 +1525,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -852,7 +1607,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -864,7 +1619,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/conversations/v1/conversation/webhook.py b/twilio/rest/conversations/v1/conversation/webhook.py index 837f88c26f..3140fd846c 100644 --- a/twilio/rest/conversations/v1/conversation/webhook.py +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,8 +26,8 @@ class WebhookInstance(InstanceResource): class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Target(object): WEBHOOK = "webhook" @@ -70,6 +71,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -178,6 +216,60 @@ async def update_async( configuration_flow_sid=configuration_flow_sid, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -209,6 +301,20 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -216,10 +322,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -228,27 +356,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebhookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebhookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, @@ -256,22 +400,46 @@ def fetch(self) -> WebhookInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, @@ -279,24 +447,35 @@ async def fetch_async(self) -> WebhookInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, configuration_filters: Union[List[str], object] = values.unset, configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance + Internal helper for update operation - :param configuration_url: The absolute url the webhook request should be sent to. - :param configuration_method: - :param configuration_filters: The list of events, firing webhook event for this Conversation. - :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -318,10 +497,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) return WebhookInstance( self._version, payload, @@ -329,16 +534,16 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, configuration_filters: Union[List[str], object] = values.unset, configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param configuration_url: The absolute url the webhook request should be sent to. :param configuration_method: @@ -346,7 +551,36 @@ async def update_async( :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,10 +602,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) return WebhookInstance( self._version, payload, @@ -379,6 +639,40 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -397,6 +691,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -430,7 +725,7 @@ def __init__(self, version: Version, conversation_sid: str): **self._solution ) - def create( + def _create( self, target: "WebhookInstance.Target", configuration_url: Union[str, object] = values.unset, @@ -439,19 +734,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param target: - :param configuration_url: The absolute url the webhook request should be sent to. - :param configuration_method: - :param configuration_filters: The list of events, firing webhook event for this Conversation. - :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. - :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -475,15 +763,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) return WebhookInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) - async def create_async( + def create_with_http_info( self, target: "WebhookInstance.Target", configuration_url: Union[str, object] = values.unset, @@ -492,9 +812,9 @@ async def create_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param target: :param configuration_url: The absolute url the webhook request should be sent to. @@ -504,7 +824,37 @@ async def create_async( :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -528,14 +878,83 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) return WebhookInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) + async def create_with_http_info_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -586,6 +1005,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -605,6 +1074,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -631,6 +1101,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -639,6 +1110,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -670,7 +1191,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -703,7 +1224,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WebhookPage: """ @@ -715,7 +1306,7 @@ def get_page(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WebhookPage: """ @@ -727,7 +1318,7 @@ async def get_page_async(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WebhookContext: """ diff --git a/twilio/rest/conversations/v1/conversation_with_participants.py b/twilio/rest/conversations/v1/conversation_with_participants.py index a818a29ca4..76e25061e5 100644 --- a/twilio/rest/conversations/v1/conversation_with_participants.py +++ b/twilio/rest/conversations/v1/conversation_with_participants.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +25,7 @@ class ConversationWithParticipantsInstance(InstanceResource): class State(object): + INITIALIZING = "initializing" INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" @@ -96,7 +98,7 @@ def __init__(self, version: Version): self._uri = "/ConversationWithParticipants" - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ConversationWithParticipantsInstance.WebhookEnabledType", object @@ -115,25 +117,12 @@ def create( bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, participant: Union[List[str], object] = values.unset, - ) -> ConversationWithParticipantsInstance: + ) -> tuple: """ - Create the ConversationWithParticipantsInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. - - :returns: The created ConversationWithParticipantsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -163,13 +152,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConversationWithParticipantsInstance(self._version, payload) - - async def create_async( + def create( self, x_twilio_webhook_enabled: Union[ "ConversationWithParticipantsInstance.WebhookEnabledType", object @@ -190,7 +177,7 @@ async def create_async( participant: Union[List[str], object] = values.unset, ) -> ConversationWithParticipantsInstance: """ - Asynchronously create the ConversationWithParticipantsInstance + Create the ConversationWithParticipantsInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -208,6 +195,106 @@ async def create_async( :returns: The created ConversationWithParticipantsInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) + return ConversationWithParticipantsInstance(self._version, payload) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationWithParticipantsInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) + instance = ConversationWithParticipantsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -236,12 +323,123 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) return ConversationWithParticipantsInstance(self._version, payload) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationWithParticipantsInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) + instance = ConversationWithParticipantsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/credential.py b/twilio/rest/conversations/v1/credential.py index f382458ba7..a1aabe7bdd 100644 --- a/twilio/rest/conversations/v1/credential.py +++ b/twilio/rest/conversations/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, type: Union["CredentialInstance.PushType", object] = values.unset, @@ -180,6 +218,72 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +311,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -214,10 +332,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -226,56 +366,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, type: Union["CredentialInstance.PushType", object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -284,19 +478,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param type: - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -316,13 +503,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, type: Union["CredentialInstance.PushType", object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -333,7 +518,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -345,84 +530,29 @@ async def update_async( :returns: The updated CredentialInstance """ - - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(sandbox), - "ApiKey": api_key, - "Secret": secret, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class CredentialPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: - """ - Build an instance of CredentialInstance - - :param payload: Payload response from the API - """ - return CredentialInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class CredentialList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the CredentialList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Credentials" - - def create( + def update_with_http_info( self, - type: "CredentialInstance.PushType", + type: Union["CredentialInstance.PushType", object] = values.unset, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, private_key: Union[str, object] = values.unset, sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> ApiResponse: """ - Create the CredentialInstance + Update the CredentialInstance and return response metadata :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -432,7 +562,35 @@ def create( :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: The created CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -446,19 +604,167 @@ def create( "Secret": secret, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of({}) headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) - async def create_async( + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def _create( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( self, type: "CredentialInstance.PushType", friendly_name: Union[str, object] = values.unset, @@ -469,7 +775,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -481,6 +787,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -499,12 +867,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -555,6 +990,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -574,6 +1059,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -600,6 +1086,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -608,6 +1095,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -674,6 +1211,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/conversations/v1/participant_conversation.py b/twilio/rest/conversations/v1/participant_conversation.py index 0938bd5421..9d6fc2566b 100644 --- a/twilio/rest/conversations/v1/participant_conversation.py +++ b/twilio/rest/conversations/v1/participant_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -104,6 +105,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstan :param payload: Payload response from the API """ + return ParticipantConversationInstance(self._version, payload) def __repr__(self) -> str: @@ -190,6 +192,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[str, object] = values.unset, @@ -213,6 +275,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -245,6 +308,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -255,6 +319,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[str, object] = values.unset, @@ -333,6 +459,88 @@ async def page_async( ) return ParticipantConversationPage(self._version, response) + def page_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantConversationPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantConversationPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ParticipantConversationPage: """ Retrieve a specific page of ParticipantConversationInstance records from the API. diff --git a/twilio/rest/conversations/v1/role.py b/twilio/rest/conversations/v1/role.py index 229e9b7dd4..f0e9160bf5 100644 --- a/twilio/rest/conversations/v1/role.py +++ b/twilio/rest/conversations/v1/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -139,6 +177,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +228,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -173,10 +249,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -185,62 +283,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -254,19 +405,39 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -280,12 +451,33 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -304,6 +496,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance(self._version, payload) def __repr__(self) -> str: @@ -328,17 +521,14 @@ def __init__(self, version: Version): self._uri = "/Roles" - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -354,17 +544,15 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RoleInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] ) -> RoleInstance: """ - Asynchronously create the RoleInstance + Create the RoleInstance :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: @@ -372,6 +560,38 @@ async def create_async( :returns: The created RoleInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -386,12 +606,45 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -442,6 +695,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -461,6 +764,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -487,6 +791,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -495,6 +800,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -561,6 +916,76 @@ async def page_async( ) return RolePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RolePage: """ Retrieve a specific page of RoleInstance records from the API. diff --git a/twilio/rest/conversations/v1/service/__init__.py b/twilio/rest/conversations/v1/service/__init__.py index 3b92c87934..e4e33fc15e 100644 --- a/twilio/rest/conversations/v1/service/__init__.py +++ b/twilio/rest/conversations/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def bindings(self) -> BindingList: """ @@ -203,6 +241,20 @@ def __init__(self, version: Version, sid: str): self._roles: Optional[RoleList] = None self._users: Optional[UserList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -210,10 +262,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -222,55 +296,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def bindings(self) -> BindingList: """ @@ -373,6 +501,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -397,13 +526,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -417,19 +545,39 @@ def create(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return ServiceInstance(self._version, payload) - async def create_async(self, friendly_name: str) -> ServiceInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance and return response metadata :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -443,12 +591,35 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ServiceInstance(self._version, payload) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -499,6 +670,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -518,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -544,6 +766,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -552,6 +775,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -618,6 +891,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/conversations/v1/service/binding.py b/twilio/rest/conversations/v1/service/binding.py index 363dab91d0..095e307625 100644 --- a/twilio/rest/conversations/v1/service/binding.py +++ b/twilio/rest/conversations/v1/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class BindingType(object): APN = "apn" GCM = "gcm" FCM = "fcm" + TWILSOCK = "twilsock" """ :ivar sid: A 34 character string that uniquely identifies this resource. @@ -74,6 +76,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -110,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -128,6 +149,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +198,20 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,10 +219,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -178,27 +253,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + :returns: The fetched BindingInstance + """ + payload, _, _ = self._fetch() return BindingInstance( self._version, payload, @@ -206,22 +297,46 @@ def fetch(self) -> BindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> BindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BindingInstance + Fetch the BindingInstance and return response metadata - :returns: The fetched BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() return BindingInstance( self._version, payload, @@ -229,6 +344,22 @@ async def fetch_async(self) -> BindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -291,7 +423,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit @@ -322,7 +454,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit @@ -340,6 +472,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -352,7 +544,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit @@ -363,6 +555,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -384,7 +577,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit @@ -395,6 +588,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -405,6 +599,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -417,7 +673,7 @@ def page( Retrieve a single page of BindingInstance records from the API. Request is executed immediately - :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state @@ -442,7 +698,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -456,7 +712,7 @@ async def page_async( Asynchronously retrieve a single page of BindingInstance records from the API. Request is executed immediately - :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state @@ -481,7 +737,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, `fcm`, or `twilsock`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BindingPage: """ @@ -493,7 +831,7 @@ def get_page(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BindingPage: """ @@ -505,7 +843,7 @@ async def get_page_async(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> BindingContext: """ diff --git a/twilio/rest/conversations/v1/service/configuration/__init__.py b/twilio/rest/conversations/v1/service/configuration/__init__.py index e37c8888c8..4cdc9de636 100644 --- a/twilio/rest/conversations/v1/service/configuration/__init__.py +++ b/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[ConfigurationContext] = None @property @@ -93,6 +95,24 @@ async def fetch_async(self) -> "ConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_conversation_creator_role_sid: Union[str, object] = values.unset, @@ -141,6 +161,54 @@ async def update_async( reachability_enabled=reachability_enabled, ) + def update_with_http_info( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + async def update_with_http_info_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,64 +238,108 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) - def fetch(self) -> ConfigurationInstance: + def _fetch(self) -> tuple: """ - Fetch the ConfigurationInstance - + Internal helper for fetch operation - :returns: The fetched ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - async def fetch_async(self) -> ConfigurationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConfigurationInstance + Fetch the ConfigurationInstance and return response metadata - :returns: The fetched ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, default_conversation_creator_role_sid: Union[str, object] = values.unset, default_conversation_role_sid: Union[str, object] = values.unset, default_chat_service_role_sid: Union[str, object] = values.unset, reachability_enabled: Union[bool, object] = values.unset, - ) -> ConfigurationInstance: + ) -> tuple: """ - Update the ConfigurationInstance + Internal helper for update operation - :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. - :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. - :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. - :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. - - :returns: The updated ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -246,30 +358,77 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def update_async( + def update_with_http_info( self, default_conversation_creator_role_sid: Union[str, object] = values.unset, default_conversation_role_sid: Union[str, object] = values.unset, default_chat_service_role_sid: Union[str, object] = values.unset, reachability_enabled: Union[bool, object] = values.unset, - ) -> ConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConfigurationInstance + Update the ConfigurationInstance and return response metadata :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. - :returns: The updated ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -288,14 +447,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def update_with_http_info_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/configuration/notification.py b/twilio/rest/conversations/v1/service/configuration/notification.py index 6aced28115..e646dbe7b9 100644 --- a/twilio/rest/conversations/v1/service/configuration/notification.py +++ b/twilio/rest/conversations/v1/service/configuration/notification.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[NotificationContext] = None @property @@ -86,6 +88,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, log_enabled: Union[bool, object] = values.unset, @@ -188,6 +208,108 @@ async def update_async( new_message_with_media_template=new_message_with_media_template, ) + def update_with_http_info( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the NotificationInstance with HTTP info + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + async def update_with_http_info_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance with HTTP info + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -217,49 +339,97 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) - def fetch(self) -> NotificationInstance: + def _fetch(self) -> tuple: """ - Fetch the NotificationInstance - + Internal helper for fetch operation - :returns: The fetched NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = self._fetch() return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - async def fetch_async(self) -> NotificationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NotificationInstance + Fetch the NotificationInstance and return response metadata - :returns: The fetched NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + payload, _, _ = await self._fetch_async() return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, log_enabled: Union[bool, object] = values.unset, new_message_enabled: Union[bool, object] = values.unset, @@ -274,25 +444,12 @@ def update( removed_from_conversation_sound: Union[str, object] = values.unset, new_message_with_media_enabled: Union[bool, object] = values.unset, new_message_with_media_template: Union[str, object] = values.unset, - ) -> NotificationInstance: + ) -> tuple: """ - Update the NotificationInstance + Internal helper for update operation - :param log_enabled: Weather the notification logging is enabled. - :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. - :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. - :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. - :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. - :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. - :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. - :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. - :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. - :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. - :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. - :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. - :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. - - :returns: The updated NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,15 +483,65 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + payload, _, _ = self._update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def update_async( + def update_with_http_info( self, log_enabled: Union[bool, object] = values.unset, new_message_enabled: Union[bool, object] = values.unset, @@ -349,9 +556,9 @@ async def update_async( removed_from_conversation_sound: Union[str, object] = values.unset, new_message_with_media_enabled: Union[bool, object] = values.unset, new_message_with_media_template: Union[str, object] = values.unset, - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the NotificationInstance + Update the NotificationInstance and return response metadata :param log_enabled: Weather the notification logging is enabled. :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. @@ -367,7 +574,49 @@ async def update_async( :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. - :returns: The updated NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -401,14 +650,119 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + payload, _, _ = await self._update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def update_with_http_info_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance and return response metadata + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/configuration/webhook.py b/twilio/rest/conversations/v1/service/configuration/webhook.py index 706f410550..eee7e3f74e 100644 --- a/twilio/rest/conversations/v1/service/configuration/webhook.py +++ b/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[WebhookContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, pre_webhook_url: Union[str, object] = values.unset, @@ -135,6 +155,54 @@ async def update_async( method=method, ) + def update_with_http_info( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + async def update_with_http_info_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,64 +232,108 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) - def fetch(self) -> WebhookInstance: + def _fetch(self) -> tuple: """ - Fetch the WebhookInstance - + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, pre_webhook_url: Union[str, object] = values.unset, post_webhook_url: Union[str, object] = values.unset, filters: Union[List[str], object] = values.unset, method: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance + Internal helper for update operation - :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. - :param post_webhook_url: The absolute url the post-event webhook request should be sent to. - :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. - :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -238,30 +350,77 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) return WebhookInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def update_async( + def update_with_http_info( self, pre_webhook_url: Union[str, object] = values.unset, post_webhook_url: Union[str, object] = values.unset, filters: Union[List[str], object] = values.unset, method: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. :param post_webhook_url: The absolute url the post-event webhook request should be sent to. :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + instance = WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -278,14 +437,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) return WebhookInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def update_with_http_info_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + instance = WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/conversation/__init__.py b/twilio/rest/conversations/v1/service/conversation/__init__.py index 0f28c4dfe2..0dcfd00023 100644 --- a/twilio/rest/conversations/v1/service/conversation/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -33,6 +34,7 @@ class State(object): INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" + INITIALIZING = "initializing" class WebhookEnabledType(object): TRUE = "true" @@ -87,6 +89,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[ConversationContext] = None @property @@ -139,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ConversationInstance": """ Fetch the ConversationInstance @@ -157,6 +194,24 @@ async def fetch_async(self) -> "ConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -257,6 +312,106 @@ async def update_async( bindings_email_name=bindings_email_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + @property def messages(self) -> MessageList: """ @@ -313,6 +468,30 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): self._participants: Optional[ParticipantList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -326,6 +505,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -334,7 +546,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -349,32 +563,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ConversationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ConversationInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() return ConversationInstance( self._version, payload, @@ -382,22 +617,46 @@ def fetch(self) -> ConversationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ConversationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConversationInstance + Fetch the ConversationInstance and return response metadata - :returns: The fetched ConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() return ConversationInstance( self._version, payload, @@ -405,7 +664,23 @@ async def fetch_async(self) -> ConversationInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -421,24 +696,12 @@ def update( unique_name: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> tuple: """ - Update the ConversationInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + Internal helper for update operation - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -471,18 +734,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConversationInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -500,7 +756,7 @@ async def update_async( bindings_email_name: Union[str, object] = values.unset, ) -> ConversationInstance: """ - Asynchronous coroutine to update the ConversationInstance + Update the ConversationInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -517,14 +773,115 @@ async def update_async( :returns: The updated ConversationInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "MessagingServiceSid": messaging_service_sid, + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, "State": state, "Timers.Inactive": timers_inactive, "Timers.Closed": timers_closed, @@ -548,10 +905,59 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) return ConversationInstance( self._version, payload, @@ -559,6 +965,63 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def messages(self) -> MessageList: """ @@ -616,6 +1079,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: :param payload: Payload response from the API """ + return ConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -649,6 +1113,60 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, x_twilio_webhook_enabled: Union[ @@ -684,6 +1202,101 @@ def create( :returns: The created ConversationInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -709,17 +1322,66 @@ def create( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + :returns: The created ConversationInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, ) - return ConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + async def create_with_http_info_async( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -735,9 +1397,9 @@ async def create_async( timers_closed: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> ApiResponse: """ - Asynchronously create the ConversationInstance + Asynchronously create the ConversationInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -752,42 +1414,26 @@ async def create_async( :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :returns: The created ConversationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "MessagingServiceSid": messaging_service_sid, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "State": state, - "Timers.Inactive": timers_inactive, - "Timers.Closed": timers_closed, - "Bindings.Email.Address": bindings_email_address, - "Bindings.Email.Name": bindings_email_name, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - "Content-Type": "application/x-www-form-urlencoded", - } - ) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, ) - - return ConversationInstance( + instance = ConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -861,6 +1507,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, start_date: Union[str, object] = values.unset, @@ -886,6 +1602,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -921,6 +1638,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -932,6 +1650,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, start_date: Union[str, object] = values.unset, @@ -972,7 +1758,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConversationPage(self._version, response, self._solution) + return ConversationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1014,7 +1800,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConversationPage(self._version, response, self._solution) + return ConversationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConversationPage: """ @@ -1026,7 +1900,7 @@ def get_page(self, target_url: str) -> ConversationPage: :returns: Page of ConversationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConversationPage(self._version, response, self._solution) + return ConversationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ConversationPage: """ @@ -1038,7 +1912,7 @@ async def get_page_async(self, target_url: str) -> ConversationPage: :returns: Page of ConversationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConversationPage(self._version, response, self._solution) + return ConversationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ConversationContext: """ diff --git a/twilio/rest/conversations/v1/service/conversation/message/__init__.py b/twilio/rest/conversations/v1/service/conversation/message/__init__.py index c4123afd34..1ae1acbaf0 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -90,6 +91,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -143,6 +145,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -161,6 +197,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -179,8 +233,8 @@ def update( :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. @@ -214,8 +268,8 @@ async def update_async( :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. @@ -231,6 +285,76 @@ async def update_async( subject=subject, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + @property def delivery_receipts(self) -> DeliveryReceiptList: """ @@ -275,6 +399,30 @@ def __init__( self._delivery_receipts: Optional[DeliveryReceiptList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -288,6 +436,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -296,7 +477,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -311,32 +494,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -345,22 +549,47 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -369,7 +598,24 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -380,19 +626,12 @@ def update( date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param subject: The subject of the message, can be up to 256 characters long. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -420,19 +659,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MessageInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -445,48 +676,27 @@ async def update_async( subject: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param subject: The subject of the message, can be up to 256 characters long. :returns: The updated MessageInstance """ - - data = values.of( - { - "Author": author, - "Body": body, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "Subject": subject, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, ) - return MessageInstance( self._version, payload, @@ -495,17 +705,193 @@ async def update_async( sid=self._solution["sid"], ) - @property - def delivery_receipts(self) -> DeliveryReceiptList: - """ - Access the delivery_receipts - """ - if self._delivery_receipts is None: - self._delivery_receipts = DeliveryReceiptList( - self._version, - self._solution["chat_service_sid"], - self._solution["conversation_sid"], - self._solution["sid"], + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["chat_service_sid"], + self._solution["conversation_sid"], + self._solution["sid"], ) return self._delivery_receipts @@ -527,6 +913,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -565,7 +952,7 @@ def __init__(self, version: Version, chat_service_sid: str, conversation_sid: st **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -579,22 +966,12 @@ def create( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param media_sid: The Media SID to be attached to the new Message. - :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. - :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. - :param subject: The subject of the message, can be up to 256 characters long. + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -621,10 +998,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) return MessageInstance( self._version, payload, @@ -632,7 +1052,7 @@ def create( conversation_sid=self._solution["conversation_sid"], ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -646,22 +1066,63 @@ async def create_async( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. :param media_sid: The Media SID to be attached to the new Message. :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. :param subject: The subject of the message, can be up to 256 characters long. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -688,10 +1149,53 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) return MessageInstance( self._version, payload, @@ -699,6 +1203,57 @@ async def create_async( conversation_sid=self._solution["conversation_sid"], ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. If you set this parameter, Twilio ignores any milliseconds in the timestamp. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + media_sid=media_sid, + content_sid=content_sid, + content_variables=content_variables, + subject=subject, + ) + instance = MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -753,6 +1308,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -774,6 +1385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -803,6 +1415,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -812,6 +1425,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -846,7 +1515,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -882,7 +1551,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -894,7 +1639,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -906,7 +1651,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py index 939b631271..d729edcd52 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[DeliveryReceiptContext] = None @property @@ -120,6 +122,24 @@ async def fetch_async(self) -> "DeliveryReceiptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,20 +182,30 @@ def __init__( **self._solution ) - def fetch(self) -> DeliveryReceiptInstance: + def _fetch(self) -> tuple: """ - Fetch the DeliveryReceiptInstance - + Internal helper for fetch operation - :returns: The fetched DeliveryReceiptInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = self._fetch() return DeliveryReceiptInstance( self._version, payload, @@ -185,22 +215,48 @@ def fetch(self) -> DeliveryReceiptInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> DeliveryReceiptInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DeliveryReceiptInstance + Fetch the DeliveryReceiptInstance and return response metadata - :returns: The fetched DeliveryReceiptInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + payload, _, _ = await self._fetch_async() return DeliveryReceiptInstance( self._version, payload, @@ -210,6 +266,24 @@ async def fetch_async(self) -> DeliveryReceiptInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -228,6 +302,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -325,6 +400,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -344,6 +469,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -370,6 +496,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -378,6 +505,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeliveryReceiptInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -409,7 +586,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) async def page_async( self, @@ -442,7 +619,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeliveryReceiptPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeliveryReceiptPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DeliveryReceiptPage: """ @@ -454,7 +701,7 @@ def get_page(self, target_url: str) -> DeliveryReceiptPage: :returns: Page of DeliveryReceiptInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: """ @@ -466,7 +713,7 @@ async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: :returns: Page of DeliveryReceiptInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DeliveryReceiptPage(self._version, response, self._solution) + return DeliveryReceiptPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DeliveryReceiptContext: """ diff --git a/twilio/rest/conversations/v1/service/conversation/participant.py b/twilio/rest/conversations/v1/service/conversation/participant.py index 03a3cead7e..960f36fd16 100644 --- a/twilio/rest/conversations/v1/service/conversation/participant.py +++ b/twilio/rest/conversations/v1/service/conversation/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -134,6 +136,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -152,6 +188,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -240,6 +294,94 @@ async def update_async( last_read_timestamp=last_read_timestamp, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -275,6 +417,30 @@ def __init__( **self._solution ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -288,6 +454,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -296,7 +495,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -311,32 +512,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ParticipantInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ParticipantInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -345,22 +567,47 @@ def fetch(self) -> ParticipantInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -369,7 +616,24 @@ async def fetch_async(self) -> ParticipantInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -383,22 +647,12 @@ def update( messaging_binding_projected_address: Union[str, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, last_read_timestamp: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Update the ParticipantInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param date_created: The date on which this resource was created. - :param date_updated: The date on which this resource was last updated. - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. - :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. - :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. - :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. - :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + Internal helper for update operation - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -429,19 +683,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ParticipantInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -457,7 +703,7 @@ async def update_async( last_read_timestamp: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronous coroutine to update the ParticipantInstance + Update the ParticipantInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param date_created: The date on which this resource was created. @@ -472,8 +718,101 @@ async def update_async( :returns: The updated ParticipantInstance """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) - data = values.of( + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( { "DateCreated": serialize.iso8601_datetime(date_created), "DateUpdated": serialize.iso8601_datetime(date_updated), @@ -501,10 +840,53 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) return ParticipantInstance( self._version, payload, @@ -513,6 +895,58 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -531,6 +965,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -569,7 +1004,7 @@ def __init__(self, version: Version, chat_service_sid: str, conversation_sid: st **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -582,21 +1017,12 @@ def create( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. - :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). - :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). - :param date_created: The date on which this resource was created. - :param date_updated: The date on which this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. - :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. - :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -622,10 +1048,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) return ParticipantInstance( self._version, payload, @@ -633,7 +1099,7 @@ def create( conversation_sid=self._solution["conversation_sid"], ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -646,9 +1112,9 @@ async def create_async( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. @@ -660,7 +1126,46 @@ async def create_async( :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -686,10 +1191,50 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) return ParticipantInstance( self._version, payload, @@ -697,6 +1242,54 @@ async def create_async( conversation_sid=self._solution["conversation_sid"], ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -747,6 +1340,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -766,6 +1409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -792,6 +1436,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -800,6 +1445,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -831,7 +1526,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -864,7 +1559,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -876,7 +1641,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -888,7 +1653,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/conversations/v1/service/conversation/webhook.py b/twilio/rest/conversations/v1/service/conversation/webhook.py index 08ec93ce4e..d95e4d364e 100644 --- a/twilio/rest/conversations/v1/service/conversation/webhook.py +++ b/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,8 +26,8 @@ class WebhookInstance(InstanceResource): class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Target(object): WEBHOOK = "webhook" @@ -74,6 +75,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -183,6 +221,60 @@ async def update_async( configuration_flow_sid=configuration_flow_sid, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -218,6 +310,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -225,10 +331,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -237,27 +365,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebhookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebhookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, @@ -266,22 +410,47 @@ def fetch(self) -> WebhookInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, @@ -290,24 +459,36 @@ async def fetch_async(self) -> WebhookInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, configuration_filters: Union[List[str], object] = values.unset, configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance - - :param configuration_url: The absolute url the webhook request should be sent to. - :param configuration_method: - :param configuration_filters: The list of events, firing webhook event for this Conversation. - :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + Internal helper for update operation - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +510,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) return WebhookInstance( self._version, payload, @@ -341,16 +548,16 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, configuration_filters: Union[List[str], object] = values.unset, configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param configuration_url: The absolute url the webhook request should be sent to. :param configuration_method: @@ -358,7 +565,37 @@ async def update_async( :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -380,10 +617,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) return WebhookInstance( self._version, payload, @@ -392,6 +655,41 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -410,6 +708,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, @@ -448,7 +747,7 @@ def __init__(self, version: Version, chat_service_sid: str, conversation_sid: st **self._solution ) - def create( + def _create( self, target: "WebhookInstance.Target", configuration_url: Union[str, object] = values.unset, @@ -457,19 +756,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param target: - :param configuration_url: The absolute url the webhook request should be sent to. - :param configuration_method: - :param configuration_filters: The list of events, firing webhook event for this Conversation. - :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. - :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. - :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,10 +785,42 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) return WebhookInstance( self._version, payload, @@ -504,7 +828,7 @@ def create( conversation_sid=self._solution["conversation_sid"], ) - async def create_async( + def create_with_http_info( self, target: "WebhookInstance.Target", configuration_url: Union[str, object] = values.unset, @@ -513,9 +837,9 @@ async def create_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param target: :param configuration_url: The absolute url the webhook request should be sent to. @@ -525,7 +849,40 @@ async def create_async( :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -549,10 +906,42 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) return WebhookInstance( self._version, payload, @@ -560,6 +949,46 @@ async def create_async( conversation_sid=self._solution["conversation_sid"], ) + async def create_with_http_info_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -610,6 +1039,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -629,6 +1108,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -655,6 +1135,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -663,6 +1144,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -694,7 +1225,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -727,7 +1258,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WebhookPage: """ @@ -739,7 +1340,7 @@ def get_page(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WebhookPage: """ @@ -751,7 +1352,7 @@ async def get_page_async(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WebhookContext: """ diff --git a/twilio/rest/conversations/v1/service/conversation_with_participants.py b/twilio/rest/conversations/v1/service/conversation_with_participants.py index ff82a8ce35..b6305a6aae 100644 --- a/twilio/rest/conversations/v1/service/conversation_with_participants.py +++ b/twilio/rest/conversations/v1/service/conversation_with_participants.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +25,7 @@ class ConversationWithParticipantsInstance(InstanceResource): class State(object): + INITIALIZING = "initializing" INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" @@ -113,7 +115,7 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ConversationWithParticipantsInstance.WebhookEnabledType", object @@ -132,25 +134,12 @@ def create( bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, participant: Union[List[str], object] = values.unset, - ) -> ConversationWithParticipantsInstance: + ) -> tuple: """ - Create the ConversationWithParticipantsInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. - - :returns: The created ConversationWithParticipantsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -180,15 +169,69 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) return ConversationWithParticipantsInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "ConversationWithParticipantsInstance.WebhookEnabledType", object @@ -207,9 +250,9 @@ async def create_async( bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, participant: Union[List[str], object] = values.unset, - ) -> ConversationWithParticipantsInstance: + ) -> ApiResponse: """ - Asynchronously create the ConversationWithParticipantsInstance + Create the ConversationWithParticipantsInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -225,7 +268,53 @@ async def create_async( :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. - :returns: The created ConversationWithParticipantsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) + instance = ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -255,14 +344,127 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) return ConversationWithParticipantsInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationWithParticipantsInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + participant=participant, + ) + instance = ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/participant_conversation.py b/twilio/rest/conversations/v1/service/participant_conversation.py index 8ec561a7d9..790e753f20 100644 --- a/twilio/rest/conversations/v1/service/participant_conversation.py +++ b/twilio/rest/conversations/v1/service/participant_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -112,6 +113,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstan :param payload: Payload response from the API """ + return ParticipantConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -207,6 +209,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[str, object] = values.unset, @@ -230,6 +292,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -262,6 +325,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -272,6 +336,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[str, object] = values.unset, @@ -309,7 +435,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantConversationPage(self._version, response, self._solution) + return ParticipantConversationPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -348,7 +476,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantConversationPage(self._version, response, self._solution) + return ParticipantConversationPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantConversationPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantConversationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantConversationPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantConversationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantConversationPage: """ @@ -360,7 +576,9 @@ def get_page(self, target_url: str) -> ParticipantConversationPage: :returns: Page of ParticipantConversationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantConversationPage(self._version, response, self._solution) + return ParticipantConversationPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> ParticipantConversationPage: """ @@ -372,7 +590,9 @@ async def get_page_async(self, target_url: str) -> ParticipantConversationPage: :returns: Page of ParticipantConversationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantConversationPage(self._version, response, self._solution) + return ParticipantConversationPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/conversations/v1/service/role.py b/twilio/rest/conversations/v1/service/role.py index 0884fb008b..f7373513a0 100644 --- a/twilio/rest/conversations/v1/service/role.py +++ b/twilio/rest/conversations/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): } self._uri = "/Services/{chat_service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,10 +257,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -193,27 +291,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, @@ -221,22 +335,46 @@ def fetch(self) -> RoleInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -244,13 +382,28 @@ async def fetch_async(self) -> RoleInstance: sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +417,19 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -275,13 +437,29 @@ def update(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +473,19 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance( self._version, payload, @@ -306,6 +493,23 @@ async def update_async(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -324,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -355,17 +560,14 @@ def __init__(self, version: Version, chat_service_sid: str): } self._uri = "/Services/{chat_service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,25 +583,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +649,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -492,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -526,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -557,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -590,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RolePage: """ @@ -602,7 +1043,7 @@ def get_page(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RolePage: """ @@ -614,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleContext: """ diff --git a/twilio/rest/conversations/v1/service/user/__init__.py b/twilio/rest/conversations/v1/service/user/__init__.py index b8cda74c8c..55e16cd848 100644 --- a/twilio/rest/conversations/v1/service/user/__init__.py +++ b/twilio/rest/conversations/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -130,6 +132,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -148,6 +184,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -200,6 +254,58 @@ async def update_async( role_sid=role_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + @property def user_conversations(self) -> UserConversationList: """ @@ -238,6 +344,30 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): self._user_conversations: Optional[UserConversationList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -251,6 +381,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -259,7 +422,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -274,32 +439,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, @@ -307,22 +493,46 @@ def fetch(self) -> UserInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -330,7 +540,23 @@ async def fetch_async(self) -> UserInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -338,16 +564,12 @@ def update( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for update operation - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -372,10 +594,35 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance( self._version, payload, @@ -383,7 +630,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -391,16 +638,45 @@ async def update_async( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The string that you assigned to describe the resource. :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -425,10 +701,35 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance( self._version, payload, @@ -436,8 +737,41 @@ async def update_async( sid=self._solution["sid"], ) - @property - def user_conversations(self) -> UserConversationList: + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def user_conversations(self) -> UserConversationList: """ Access the user_conversations """ @@ -467,6 +801,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -498,7 +833,7 @@ def __init__(self, version: Version, chat_service_sid: str): } self._uri = "/Services/{chat_service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -507,17 +842,12 @@ def create( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -539,15 +869,43 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -556,9 +914,9 @@ async def create_async( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -566,7 +924,35 @@ async def create_async( :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -588,14 +974,75 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -646,6 +1093,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -665,6 +1162,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -691,6 +1189,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -699,6 +1198,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -730,7 +1279,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -763,7 +1312,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -775,7 +1394,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -787,7 +1406,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserContext: """ diff --git a/twilio/rest/conversations/v1/service/user/user_conversation.py b/twilio/rest/conversations/v1/service/user/user_conversation.py index 4f1727f8e8..7a05c5fc73 100644 --- a/twilio/rest/conversations/v1/service/user/user_conversation.py +++ b/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -100,6 +101,7 @@ def __init__( "user_sid": user_sid, "conversation_sid": conversation_sid or self.conversation_sid, } + self._context: Optional[UserConversationContext] = None @property @@ -137,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserConversationInstance": """ Fetch the UserConversationInstance @@ -155,6 +175,24 @@ async def fetch_async(self) -> "UserConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -201,6 +239,52 @@ async def update_async( last_read_message_index=last_read_message_index, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +324,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserConversationInstance @@ -247,10 +345,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -259,27 +379,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserConversationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserConversationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = self._fetch() return UserConversationInstance( self._version, payload, @@ -288,22 +424,47 @@ def fetch(self) -> UserConversationInstance: conversation_sid=self._solution["conversation_sid"], ) - async def fetch_async(self) -> UserConversationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserConversationInstance + Fetch the UserConversationInstance and return response metadata - :returns: The fetched UserConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = await self._fetch_async() return UserConversationInstance( self._version, payload, @@ -312,22 +473,36 @@ async def fetch_async(self) -> UserConversationInstance: conversation_sid=self._solution["conversation_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, notification_level: Union[ "UserConversationInstance.NotificationLevel", object ] = values.unset, last_read_timestamp: Union[datetime, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, - ) -> UserConversationInstance: + ) -> tuple: """ - Update the UserConversationInstance + Internal helper for update operation - :param notification_level: - :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. - :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. - - :returns: The updated UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,10 +518,32 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) return UserConversationInstance( self._version, payload, @@ -355,22 +552,50 @@ def update( conversation_sid=self._solution["conversation_sid"], ) - async def update_async( + def update_with_http_info( self, notification_level: Union[ "UserConversationInstance.NotificationLevel", object ] = values.unset, last_read_timestamp: Union[datetime, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, - ) -> UserConversationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserConversationInstance + Update the UserConversationInstance and return response metadata :param notification_level: :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. - :returns: The updated UserConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -386,10 +611,32 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) return UserConversationInstance( self._version, payload, @@ -398,6 +645,37 @@ async def update_async( conversation_sid=self._solution["conversation_sid"], ) + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance and return response metadata + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -416,6 +694,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, @@ -506,6 +785,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -525,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -551,6 +881,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -559,6 +890,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -590,7 +971,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -623,7 +1004,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserConversationPage: """ @@ -635,7 +1086,7 @@ def get_page(self, target_url: str) -> UserConversationPage: :returns: Page of UserConversationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserConversationPage: """ @@ -647,7 +1098,7 @@ async def get_page_async(self, target_url: str) -> UserConversationPage: :returns: Page of UserConversationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) def get(self, conversation_sid: str) -> UserConversationContext: """ diff --git a/twilio/rest/conversations/v1/user/__init__.py b/twilio/rest/conversations/v1/user/__init__.py index fe5d12f095..b149577147 100644 --- a/twilio/rest/conversations/v1/user/__init__.py +++ b/twilio/rest/conversations/v1/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -122,6 +124,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -140,6 +176,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -192,6 +246,58 @@ async def update_async( role_sid=role_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + @property def user_conversations(self) -> UserConversationList: """ @@ -228,6 +334,30 @@ def __init__(self, version: Version, sid: str): self._user_conversations: Optional[UserConversationList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -241,6 +371,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -249,7 +412,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -264,61 +429,120 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -326,16 +550,12 @@ def update( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for update operation - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -360,13 +580,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return UserInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -376,7 +594,7 @@ async def update_async( role_sid: Union[str, object] = values.unset, ) -> UserInstance: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The string that you assigned to describe the resource. @@ -385,6 +603,57 @@ async def update_async( :returns: The updated UserInstance """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -408,12 +677,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def user_conversations(self) -> UserConversationList: """ @@ -444,6 +766,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance(self._version, payload) def __repr__(self) -> str: @@ -468,7 +791,7 @@ def __init__(self, version: Version): self._uri = "/Users" - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -477,17 +800,12 @@ def create( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -509,13 +827,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return UserInstance(self._version, payload) - - async def create_async( + def create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -526,7 +842,7 @@ async def create_async( role_sid: Union[str, object] = values.unset, ) -> UserInstance: """ - Asynchronously create the UserInstance + Create the UserInstance :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -536,6 +852,62 @@ async def create_async( :returns: The created UserInstance """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload) + + def create_with_http_info( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -556,12 +928,71 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) return UserInstance(self._version, payload) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -612,6 +1043,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -631,6 +1112,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -657,6 +1139,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -665,6 +1148,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -731,6 +1264,76 @@ async def page_async( ) return UserPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> UserPage: """ Retrieve a specific page of UserInstance records from the API. diff --git a/twilio/rest/conversations/v1/user/user_conversation.py b/twilio/rest/conversations/v1/user/user_conversation.py index 16ce2c2418..c6dd85ac39 100644 --- a/twilio/rest/conversations/v1/user/user_conversation.py +++ b/twilio/rest/conversations/v1/user/user_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,6 +99,7 @@ def __init__( "user_sid": user_sid, "conversation_sid": conversation_sid or self.conversation_sid, } + self._context: Optional[UserConversationContext] = None @property @@ -134,6 +136,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserConversationInstance": """ Fetch the UserConversationInstance @@ -152,6 +172,24 @@ async def fetch_async(self) -> "UserConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -198,6 +236,52 @@ async def update_async( last_read_message_index=last_read_message_index, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -229,6 +313,20 @@ def __init__(self, version: Version, user_sid: str, conversation_sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserConversationInstance @@ -236,10 +334,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -248,27 +368,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserConversationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserConversationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = self._fetch() return UserConversationInstance( self._version, payload, @@ -276,22 +412,46 @@ def fetch(self) -> UserConversationInstance: conversation_sid=self._solution["conversation_sid"], ) - async def fetch_async(self) -> UserConversationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserConversationInstance + Fetch the UserConversationInstance and return response metadata - :returns: The fetched UserConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + payload, _, _ = await self._fetch_async() return UserConversationInstance( self._version, payload, @@ -299,22 +459,35 @@ async def fetch_async(self) -> UserConversationInstance: conversation_sid=self._solution["conversation_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, notification_level: Union[ "UserConversationInstance.NotificationLevel", object ] = values.unset, last_read_timestamp: Union[datetime, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, - ) -> UserConversationInstance: + ) -> tuple: """ - Update the UserConversationInstance - - :param notification_level: - :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. - :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + Internal helper for update operation - :returns: The updated UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -330,10 +503,32 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) return UserConversationInstance( self._version, payload, @@ -341,22 +536,49 @@ def update( conversation_sid=self._solution["conversation_sid"], ) - async def update_async( + def update_with_http_info( self, notification_level: Union[ "UserConversationInstance.NotificationLevel", object ] = values.unset, last_read_timestamp: Union[datetime, object] = values.unset, last_read_message_index: Union[int, object] = values.unset, - ) -> UserConversationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserConversationInstance + Update the UserConversationInstance and return response metadata :param notification_level: :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. - :returns: The updated UserConversationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -372,10 +594,32 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) return UserConversationInstance( self._version, payload, @@ -383,6 +627,36 @@ async def update_async( conversation_sid=self._solution["conversation_sid"], ) + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance and return response metadata + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + instance = UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -401,6 +675,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, user_sid=self._solution["user_sid"] ) @@ -482,6 +757,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -501,6 +826,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -527,6 +853,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -535,6 +862,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserConversationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -566,7 +943,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -599,7 +976,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserConversationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserConversationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserConversationPage: """ @@ -611,7 +1058,7 @@ def get_page(self, target_url: str) -> UserConversationPage: :returns: Page of UserConversationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserConversationPage: """ @@ -623,7 +1070,7 @@ async def get_page_async(self, target_url: str) -> UserConversationPage: :returns: Page of UserConversationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserConversationPage(self._version, response, self._solution) + return UserConversationPage(self._version, response, solution=self._solution) def get(self, conversation_sid: str) -> UserConversationContext: """ diff --git a/twilio/rest/conversations/v2/__init__.py b/twilio/rest/conversations/v2/__init__.py new file mode 100644 index 0000000000..20b77dcd96 --- /dev/null +++ b/twilio/rest/conversations/v2/__init__.py @@ -0,0 +1,104 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.conversations.v2.action import ActionList +from twilio.rest.conversations.v2.communication import CommunicationList +from twilio.rest.conversations.v2.configuration import ConfigurationList +from twilio.rest.conversations.v2.conversation import ConversationList +from twilio.rest.conversations.v2.operation import OperationList +from twilio.rest.conversations.v2.participant import ParticipantList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Conversations + + :param domain: The Twilio.conversations domain + """ + super().__init__(domain, "v2") + self._configurations: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._operations: Optional[OperationList] = None + + def actions(self, conversation_id: str, action_id: str = None): + """ + Access the ActionList resource + + :param conversation_id: + + :param action_id: Optional instance ID to directly access ActionContext + :returns: ActionList instance if action_id is None, otherwise ActionContext + """ + list_instance = ActionList(self, conversation_id) + if action_id is not None: + return list_instance(action_id) + return list_instance + + def communications(self, conversation_id: str, communication_id: str = None): + """ + Access the CommunicationList resource + + :param conversation_id: + + :param communication_id: Optional instance ID to directly access CommunicationContext + :returns: CommunicationList instance if communication_id is None, otherwise CommunicationContext + """ + list_instance = CommunicationList(self, conversation_id) + if communication_id is not None: + return list_instance(communication_id) + return list_instance + + @property + def configurations(self) -> ConfigurationList: + if self._configurations is None: + self._configurations = ConfigurationList(self) + return self._configurations + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def participants(self, conversation_id: str, participant_id: str = None): + """ + Access the ParticipantList resource + + :param conversation_id: + + :param participant_id: Optional instance ID to directly access ParticipantContext + :returns: ParticipantList instance if participant_id is None, otherwise ParticipantContext + """ + list_instance = ParticipantList(self, conversation_id) + if participant_id is not None: + return list_instance(participant_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/action.py b/twilio/rest/conversations/v2/action.py new file mode 100644 index 0000000000..6f907b17d7 --- /dev/null +++ b/twilio/rest/conversations/v2/action.py @@ -0,0 +1,527 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ActionInstance(InstanceResource): + + class ConversationsV2ActionStatus(object): + PENDING = "PENDING" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + class ConversationsV2Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + + """ + :ivar id: Unique identifier for this Action. + :ivar type: The type of action. Accepted values: SEND_MESSAGE. + :ivar status: + :ivar conversation_id: The conversation this action belongs to. + :ivar related: Named identifiers from downstream. For SEND_MESSAGE: - messageSid: The downstream message SID (present when PENDING or COMPLETED) - communicationId: The Communication ID (present when COMPLETED) + :ivar created_at: Timestamp when the action was created. + :ivar updated_at: Timestamp when the action was last updated. + :ivar completed_at: Timestamp when the action reached a terminal status. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_id: str, + action_id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.type: Optional[str] = payload.get("type") + self.status: Optional["ActionInstance.str"] = payload.get("status") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.related: Optional[Dict[str, str]] = payload.get("related") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_id is not None or action_id is not None: + self._solution = { + "conversation_id": conversation_id, + "action_id": action_id, + } + + self._context: Optional[ActionContext] = None + + @property + def _proxy(self) -> "ActionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ActionContext for this ActionInstance + """ + if self._context is None: + self._context = ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return self._context + + def fetch(self) -> "ActionInstance": + """ + Fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ActionInstance": + """ + Asynchronous coroutine to fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ActionContext(InstanceContext): + + def __init__(self, version: Version, conversation_id: str, action_id: str): + """ + Initialize the ActionContext + + :param version: Version that contains the resource + :param conversation_id: + :param action_id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + "action_id": action_id, + } + self._uri = "/Conversations/{conversation_id}/Actions/{action_id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ActionInstance: + """ + Fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + payload, _, _ = self._fetch() + return ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ActionInstance: + """ + Asynchronous coroutine to fetch the ActionInstance + + + :returns: The fetched ActionInstance + """ + payload, _, _ = await self._fetch_async() + return ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ActionInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + action_id=self._solution["action_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ActionList(ListResource): + + class ConversationsV2SendMessageContent(object): + """ + :ivar text: Plain text message body. + :ivar content_id: Content template ID (HX... format). When provided, the template is rendered with the variables map and sent to the recipient. + :ivar variables: Variables to substitute into the content template. + :ivar media_urls: URLs of media attachments to include with the message. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + self.content_id: Optional[str] = payload.get("contentId") + self.variables: Optional[Dict[str, str]] = payload.get("variables") + self.media_urls: Optional[List[str]] = payload.get("mediaUrls") + + def to_dict(self): + return { + "text": self.text, + "contentId": self.content_id, + "variables": self.variables, + "mediaUrls": self.media_urls, + } + + class ConversationsV2SendMessageParticipant(object): + """ + :ivar participant_id: Participant ID to resolve address from. + :ivar address: Explicit address formatted according to channel type. + :ivar channel: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.participant_id: Optional[str] = payload.get("participantId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional["ActionInstance.ConversationsV2Channel"] = ( + payload.get("channel") + ) + + def to_dict(self): + return { + "participantId": self.participant_id, + "address": self.address, + "channel": self.channel, + } + + class ConversationsV2SendMessagePayload(object): + """ + :ivar _from: + :ivar to: The recipients of this action. + :ivar content: + :ivar channel_settings: Channel-specific parameters forwarded as-is to the downstream sending service. Allows passing backend-specific fields without requiring API changes. + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[ActionList.ConversationsV2SendMessageParticipant] = ( + payload.get("from") + ) + self.to: Optional[ + List[ActionList.ConversationsV2SendMessageParticipant] + ] = payload.get("to") + self.content: Optional[ActionList.ConversationsV2SendMessageContent] = ( + payload.get("content") + ) + self.channel_settings: Optional[Dict[str, object]] = payload.get( + "channelSettings" + ) + + def to_dict(self): + return { + "from": self._from.to_dict() if self._from is not None else None, + "to": [to.to_dict() for to in self.to] if self.to is not None else None, + "content": self.content.to_dict() if self.content is not None else None, + "channelSettings": self.channel_settings, + } + + class CreateConversationActionRequest(object): + """ + :ivar type: Action type discriminator. Accepted values: SEND_MESSAGE. + :ivar payload: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.payload: Optional[ActionList.ConversationsV2SendMessagePayload] = ( + payload.get("payload") + ) + + def to_dict(self): + return { + "type": self.type, + "payload": self.payload.to_dict() if self.payload is not None else None, + } + + def __init__(self, version: Version, conversation_id: str): + """ + Initialize the ActionList + + :param version: Version that contains the resource + :param conversation_id: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + } + self._uri = "/Conversations/{conversation_id}/Actions".format(**self._solution) + + def _create( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_action_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ActionInstance: + """ + Create the ActionInstance + + :param create_conversation_action_request: The action to perform. + + :returns: The created ActionInstance + """ + payload, _, _ = self._create( + create_conversation_action_request=create_conversation_action_request + ) + return ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def create_with_http_info( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ApiResponse: + """ + Create the ActionInstance and return response metadata + + :param create_conversation_action_request: The action to perform. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_conversation_action_request=create_conversation_action_request + ) + instance = ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_action_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ActionInstance: + """ + Asynchronously create the ActionInstance + + :param create_conversation_action_request: The action to perform. + + :returns: The created ActionInstance + """ + payload, _, _ = await self._create_async( + create_conversation_action_request=create_conversation_action_request + ) + return ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + async def create_with_http_info_async( + self, create_conversation_action_request: CreateConversationActionRequest + ) -> ApiResponse: + """ + Asynchronously create the ActionInstance and return response metadata + + :param create_conversation_action_request: The action to perform. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_conversation_action_request=create_conversation_action_request + ) + instance = ActionInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, action_id: str) -> ActionContext: + """ + Constructs a ActionContext + + :param action_id: + """ + return ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=action_id, + ) + + def __call__(self, action_id: str) -> ActionContext: + """ + Constructs a ActionContext + + :param action_id: + """ + return ActionContext( + self._version, + conversation_id=self._solution["conversation_id"], + action_id=action_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/communication.py b/twilio/rest/conversations/v2/communication.py new file mode 100644 index 0000000000..adecbdd956 --- /dev/null +++ b/twilio/rest/conversations/v2/communication.py @@ -0,0 +1,1077 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class CommunicationInstance(InstanceResource): + + class ConversationsV2Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + + class ConversationsV2RecipientDeliveryStatus(object): + INITIATED = "INITIATED" + IN_PROGRESS = "IN_PROGRESS" + DELIVERED = "DELIVERED" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + """ + :ivar id: Communication ID. + :ivar conversation_id: Conversation ID. + :ivar account_id: Account ID. + :ivar author: + :ivar content: + :ivar channel_id: Channel-specific reference ID. + :ivar resource_id: External resource identifier for this Communication (e.g. MessageSid for SMS/RCS/WhatsApp, TranscriptionSid + MessageIndex for Voice). When set, used for Communication deduplication/uniqueness within a Conversation. + :ivar recipients: Communication recipients. + :ivar created_at: Timestamp when this Communication was created. + :ivar updated_at: Timestamp when this Communication was last updated. + :ivar occurred_at: ISO 8601 timestamp when the communication occurred. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.account_id: Optional[str] = payload.get("accountId") + self.author: Optional[str] = payload.get("author") + self.content: Optional[str] = payload.get("content") + self.channel_id: Optional[str] = payload.get("channelId") + self.resource_id: Optional[str] = payload.get("resourceId") + self.recipients: Optional[List[str]] = payload.get("recipients") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_id is not None or id is not None: + self._solution = { + "conversation_id": conversation_id, + "id": id, + } + + self._context: Optional[CommunicationContext] = None + + @property + def _proxy(self) -> "CommunicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommunicationContext for this CommunicationInstance + """ + if self._context is None: + self._context = CommunicationContext( + self._version, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "CommunicationInstance": + """ + Fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommunicationInstance": + """ + Asynchronous coroutine to fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommunicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommunicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommunicationContext(InstanceContext): + + def __init__(self, version: Version, conversation_id: str, id: str): + """ + Initialize the CommunicationContext + + :param version: Version that contains the resource + :param conversation_id: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + "id": id, + } + self._uri = "/Conversations/{conversation_id}/Communications/{id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommunicationInstance: + """ + Fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + payload, _, _ = self._fetch() + return CommunicationInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommunicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CommunicationInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CommunicationInstance: + """ + Asynchronous coroutine to fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + payload, _, _ = await self._fetch_async() + return CommunicationInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommunicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CommunicationInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CommunicationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> CommunicationInstance: + """ + Build an instance of CommunicationInstance + + :param payload: Payload response from the API + """ + + return CommunicationInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CommunicationList(ListResource): + + class ContentTranscriptionTranscription(object): + """ + :ivar channel: + :ivar confidence: + :ivar engine: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[int] = payload.get("channel") + self.confidence: Optional[float] = payload.get("confidence") + self.engine: Optional[str] = payload.get("engine") + + def to_dict(self): + return { + "channel": self.channel, + "confidence": self.confidence, + "engine": self.engine, + } + + class ConversationsV2ContentTranscriptionTranscription(object): + """ + :ivar channel: Audio channel identifier (0 for inbound, 1 for outbound). + :ivar confidence: Overall confidence score for the transcription (0.0-1.0). + :ivar engine: Transcription engine used. + :ivar words: Word-level transcription data with timing information. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[int] = payload.get("channel") + self.confidence: Optional[float] = payload.get("confidence") + self.engine: Optional[str] = payload.get("engine") + self.words: Optional[ + List[ConversationsV2ContentTranscriptionTranscriptionWords] + ] = payload.get("words") + + def to_dict(self): + return { + "channel": self.channel, + "confidence": self.confidence, + "engine": self.engine, + "words": ( + [words.to_dict() for words in self.words] + if self.words is not None + else None + ), + } + + class ConversationsV2ContentTranscriptionTranscriptionWords(object): + """ + :ivar text: The transcribed word. + :ivar start_time: Start timestamp of this word. + :ivar end_time: End timestamp of this word. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + self.start_time: Optional[datetime] = payload.get("startTime") + self.end_time: Optional[datetime] = payload.get("endTime") + + def to_dict(self): + return { + "text": self.text, + "startTime": self.start_time, + "endTime": self.end_time, + } + + class CreateCommunicationInConversationRequest(object): + """ + :ivar author: + :ivar content: + :ivar channel_id: + :ivar recipients: + :ivar occurred_at: Timestamp when this Communication occurred. If omitted, the server uses the current time. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.author: Optional[ + CommunicationList.CreateCommunicationInConversationRequestAuthor + ] = payload.get("author") + self.content: Optional[ + CommunicationList.CreateCommunicationInConversationRequestContent + ] = payload.get("content") + self.channel_id: Optional[str] = payload.get("channelId") + self.recipients: Optional[ + List[ + CommunicationList.CreateCommunicationInConversationRequestRecipients + ] + ] = payload.get("recipients") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + + def to_dict(self): + return { + "author": self.author.to_dict() if self.author is not None else None, + "content": self.content.to_dict() if self.content is not None else None, + "channelId": self.channel_id, + "recipients": ( + [recipients.to_dict() for recipients in self.recipients] + if self.recipients is not None + else None + ), + "occurredAt": self.occurred_at, + } + + class CreateCommunicationInConversationRequestAuthor(object): + """ + :ivar address: + :ivar channel: Channel type for a Communication address. + :ivar participant_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.channel: Optional["CommunicationInstance.str"] = payload.get("channel") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "channel": self.channel, + "participantId": self.participant_id, + } + + class CreateCommunicationInConversationRequestContent(object): + """ + :ivar type: + :ivar text: + :ivar transcription: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["CommunicationInstance.str"] = payload.get("type") + self.text: Optional[str] = payload.get("text") + self.transcription: Optional[ + CommunicationList.ContentTranscriptionTranscription + ] = payload.get("transcription") + + def to_dict(self): + return { + "type": self.type, + "text": self.text, + "transcription": ( + self.transcription.to_dict() + if self.transcription is not None + else None + ), + } + + class CreateCommunicationInConversationRequestRecipients(object): + """ + :ivar address: + :ivar channel: Channel type for a Communication address. + :ivar participant_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.channel: Optional["CommunicationInstance.str"] = payload.get("channel") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "channel": self.channel, + "participantId": self.participant_id, + } + + def __init__(self, version: Version, conversation_id: str): + """ + Initialize the CommunicationList + + :param version: Version that contains the resource + :param conversation_id: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + } + self._uri = "/Conversations/{conversation_id}/Communications".format( + **self._solution + ) + + def _create( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_communication_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> CommunicationInstance: + """ + Create the CommunicationInstance + + :param create_communication_in_conversation_request: + + :returns: The created CommunicationInstance + """ + payload, _, _ = self._create( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + return CommunicationInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def create_with_http_info( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the CommunicationInstance and return response metadata + + :param create_communication_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + instance = CommunicationInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_communication_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> CommunicationInstance: + """ + Asynchronously create the CommunicationInstance + + :param create_communication_in_conversation_request: + + :returns: The created CommunicationInstance + """ + payload, _, _ = await self._create_async( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + return CommunicationInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + async def create_with_http_info_async( + self, + create_communication_in_conversation_request: Union[ + CreateCommunicationInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommunicationInstance and return response metadata + + :param create_communication_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_communication_in_conversation_request=create_communication_in_conversation_request + ) + instance = CommunicationInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommunicationInstance]: + """ + Streams CommunicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommunicationInstance]: + """ + Asynchronously streams CommunicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_id=channel_id, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommunicationInstance]: + """ + Lists CommunicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommunicationInstance]: + """ + Asynchronously lists CommunicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CommunicationInstance and returns headers from first page + + + :param str channel_id: Resource identifier to filter communications + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> CommunicationPage: + """ + Retrieve a single page of CommunicationInstance records from the API. + Request is executed immediately + + :param channel_id: Resource identifier to filter communications + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of CommunicationInstance + """ + data = values.of( + { + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommunicationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> CommunicationPage: + """ + Asynchronously retrieve a single page of CommunicationInstance records from the API. + Request is executed immediately + + :param channel_id: Resource identifier to filter communications + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of CommunicationInstance + """ + data = values.of( + { + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommunicationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param channel_id: Resource identifier to filter communications + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommunicationPage, status code, and headers + """ + data = values.of( + { + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommunicationPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param channel_id: Resource identifier to filter communications + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommunicationPage, status code, and headers + """ + data = values.of( + { + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommunicationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> CommunicationPage: + """ + Retrieve a specific page of CommunicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommunicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommunicationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> CommunicationPage: + """ + Asynchronously retrieve a specific page of CommunicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommunicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommunicationPage(self._version, response, solution=self._solution) + + def get(self, id: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param id: + """ + return CommunicationContext( + self._version, conversation_id=self._solution["conversation_id"], id=id + ) + + def __call__(self, id: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param id: + """ + return CommunicationContext( + self._version, conversation_id=self._solution["conversation_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/configuration.py b/twilio/rest/conversations/v2/configuration.py new file mode 100644 index 0000000000..fb481bcc49 --- /dev/null +++ b/twilio/rest/conversations/v2/configuration.py @@ -0,0 +1,1695 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConfigurationInstance(InstanceResource): + + class ConversationsV2ConversationGroupingType(object): + GROUP_BY_PROFILE = "GROUP_BY_PROFILE" + GROUP_BY_PARTICIPANT_ADDRESSES = "GROUP_BY_PARTICIPANT_ADDRESSES" + GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE = ( + "GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE" + ) + + """ + :ivar status_url: URL to poll for operation status. + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + :ivar id: Configuration ID. + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the Configuration. Allows spaces and special characters, typically limited to a paragraph of text. This serves as a descriptive field rather than just a name. + :ivar conversation_grouping_type: + :ivar memory_store_id: Memory Store ID for Profile resolution. + :ivar channel_settings: Channel-specific configuration settings by channel type. Keys should be valid channel types (`VOICE`, `SMS`, `RCS`, `WHATSAPP`, `CHAT`). + :ivar status_callbacks: List of default webhook configurations applied to Conversations under this Configuration. + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + :ivar conversations_v1_bridge: + :ivar created_at: Timestamp when this Configuration was created. + :ivar updated_at: Timestamp when this Configuration was last updated. + :ivar version: Version number used for optimistic locking. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.status_url: Optional[str] = payload.get("statusUrl") + self.related: Optional[Dict[str, str]] = payload.get("related") + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional[ + "ConfigurationInstance.ConversationsV2ConversationGroupingType" + ] = payload.get("conversationGroupingType") + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[Dict[str, ConversationsV2ChannelSetting]] = ( + payload.get("channelSettings") + ) + self.status_callbacks: Optional[List[ConversationsV2StatusCallbackConfig]] = ( + payload.get("statusCallbacks") + ) + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + self.conversations_v1_bridge: Optional[ConversationsV2ConversationsV1Bridge] = ( + payload.get("conversationsV1Bridge") + ) + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = payload.get("version") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + idempotency_key=idempotency_key, + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + idempotency_key=idempotency_key, + ) + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + idempotency_key=idempotency_key, + ) + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + idempotency_key=idempotency_key, + ) + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + async def update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + def update_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + async def update_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Configurations/{id}".format(**self._solution) + + def _delete(self, idempotency_key: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(idempotency_key=idempotency_key) + return success + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(idempotency_key=idempotency_key) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(idempotency_key=idempotency_key) + return success + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + idempotency_key=idempotency_key + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + if not ( + idempotency_key is values.unset + or (isinstance(idempotency_key, str) and not idempotency_key) + ): + headers["Idempotency-Key"] = idempotency_key + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + if not ( + idempotency_key is values.unset + or (isinstance(idempotency_key, str) and not idempotency_key) + ): + headers["Idempotency-Key"] = idempotency_key + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + update_configuration_request: Union[ + UpdateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param update_configuration_request: The configuration to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + idempotency_key=idempotency_key, + update_configuration_request=update_configuration_request, + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConfigurationInstance: + """ + Build an instance of ConfigurationInstance + + :param payload: Payload response from the API + """ + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfigurationList(ListResource): + + class ConversationsV2CaptureRule(object): + """ + :ivar _from: The from address. Use `*` for wildcard to match any from address. + :ivar to: The to address. Use `*` for wildcard to match any to address. + :ivar metadata: Additional matching criteria for the capture rule. For voice calls, can include `callType` (`PSTN`, `SIP`, and similar). + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class ConversationsV2ChannelSetting(object): + """ + :ivar status_timeouts: + :ivar capture_rules: Array of capture rules with from/to addresses and optional metadata. Use `*` for wildcard matching in either direction. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ConversationsV2StatusTimeouts] = payload.get( + "statusTimeouts" + ) + self.capture_rules: Optional[List[ConversationsV2CaptureRule]] = ( + payload.get("captureRules") + ) + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class ConversationsV2ConversationsV1Bridge(object): + """ + :ivar service_id: The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.service_id: Optional[str] = payload.get("serviceId") + + def to_dict(self): + return { + "serviceId": self.service_id, + } + + class ConversationsV2StatusCallbackConfig(object): + """ + :ivar url: Destination URL for webhooks. + :ivar method: HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional[str] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class ConversationsV2StatusTimeouts(object): + """ + :ivar inactive: Inactivity timeout in minutes. + :ivar closed: Close timeout in minutes. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class CreateConfigurationRequest(object): + """ + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the configuration. + :ivar conversation_grouping_type: Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + :ivar memory_store_id: The memory store ID that Conversation Orchestrator uses for profile resolution. + :ivar channel_settings: + :ivar status_callbacks: A list of webhook configurations. + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + :ivar conversations_v1_bridge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = ( + payload.get("conversationGroupingType") + ) + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[ + Dict[str, CreateConfigurationRequestChannelSettingsValue] + ] = payload.get("channelSettings") + self.status_callbacks: Optional[ + List[ConfigurationList.CreateConfigurationRequestStatusCallbacks] + ] = payload.get("statusCallbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + self.conversations_v1_bridge: Optional[ + ConfigurationList.CreateConfigurationRequestConversationsV1Bridge + ] = payload.get("conversationsV1Bridge") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "conversationGroupingType": self.conversation_grouping_type, + "memoryStoreId": self.memory_store_id, + "channelSettings": ( + {k: v.to_dict() for k, v in self.channel_settings.items()} + if self.channel_settings is not None + else None + ), + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + "memoryExtractionEnabled": self.memory_extraction_enabled, + "conversationsV1Bridge": ( + self.conversations_v1_bridge.to_dict() + if self.conversations_v1_bridge is not None + else None + ), + } + + class CreateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ + CreateConfigurationRequestChannelSettingsValueStatusTimeouts + ] = payload.get("statusTimeouts") + self.capture_rules: Optional[ + List[CreateConfigurationRequestChannelSettingsValueCaptureRules] + ] = payload.get("captureRules") + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class CreateConfigurationRequestChannelSettingsValueCaptureRules(object): + """ + :ivar _from: The from address. Use '*' for wildcard. + :ivar to: The to address. Use '*' for wildcard. + :ivar metadata: + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class CreateConfigurationRequestChannelSettingsValueStatusTimeouts(object): + """ + :ivar inactive: The inactivity timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + :ivar closed: The close timeout in minutes. For more information, see [Conversation lifecycle](/docs/platform/conversations/concepts/lifecycle). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class CreateConfigurationRequestConversationsV1Bridge(object): + """ + :ivar service_id: The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.service_id: Optional[str] = payload.get("serviceId") + + def to_dict(self): + return { + "serviceId": self.service_id, + } + + class CreateConfigurationRequestStatusCallbacks(object): + """ + :ivar url: The destination URL for webhooks. + :ivar method: The HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class UpdateConfigurationRequest(object): + """ + :ivar display_name: A human-readable name for the configuration. Limited to 32 characters. + :ivar description: Human-readable description for the configuration. + :ivar conversation_grouping_type: Type of Conversation grouping strategy: - `GROUP_BY_PROFILE`: Groups Communications by resolved Profile from the Memory Store. A Profile is looked up or created for `CUSTOMER` Participant types. All Communications from the same Profile are in the same Conversation, regardless of address or channel. - `GROUP_BY_PARTICIPANT_ADDRESSES`: Groups Communications by Participant addresses across all channels. A customer using +18005550100 will be in the same Conversation whether they contact by SMS, WhatsApp, or RCS. - `GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE`: Groups Communications by both Participant addresses AND channel. A customer using +18005550100 by SMS will be in a different Conversation than the same customer by Voice. + :ivar memory_store_id: The Memory Store ID for profile resolution. + :ivar channel_settings: + :ivar status_callbacks: + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + :ivar memory_extraction_enabled: Whether memory extraction is enabled for conversations under this configuration. Defaults to false. + :ivar conversations_v1_bridge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.conversation_grouping_type: Optional["ConfigurationInstance.str"] = ( + payload.get("conversationGroupingType") + ) + self.memory_store_id: Optional[str] = payload.get("memoryStoreId") + self.channel_settings: Optional[ + Dict[str, UpdateConfigurationRequestChannelSettingsValue] + ] = payload.get("channelSettings") + self.status_callbacks: Optional[ + List[ConfigurationList.UpdateConfigurationRequestStatusCallbacks] + ] = payload.get("statusCallbacks") + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.memory_extraction_enabled: Optional[bool] = payload.get( + "memoryExtractionEnabled" + ) + self.conversations_v1_bridge: Optional[ + ConfigurationList.CreateConfigurationRequestConversationsV1Bridge + ] = payload.get("conversationsV1Bridge") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "conversationGroupingType": self.conversation_grouping_type, + "memoryStoreId": self.memory_store_id, + "channelSettings": ( + {k: v.to_dict() for k, v in self.channel_settings.items()} + if self.channel_settings is not None + else None + ), + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + "memoryExtractionEnabled": self.memory_extraction_enabled, + "conversationsV1Bridge": ( + self.conversations_v1_bridge.to_dict() + if self.conversations_v1_bridge is not None + else None + ), + } + + class UpdateConfigurationRequestChannelSettingsValue(object): + """ + :ivar status_timeouts: + :ivar capture_rules: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_timeouts: Optional[ + UpdateConfigurationRequestChannelSettingsValueStatusTimeouts + ] = payload.get("statusTimeouts") + self.capture_rules: Optional[ + List[UpdateConfigurationRequestChannelSettingsValueCaptureRules] + ] = payload.get("captureRules") + + def to_dict(self): + return { + "statusTimeouts": ( + self.status_timeouts.to_dict() + if self.status_timeouts is not None + else None + ), + "captureRules": ( + [capture_rules.to_dict() for capture_rules in self.capture_rules] + if self.capture_rules is not None + else None + ), + } + + class UpdateConfigurationRequestChannelSettingsValueCaptureRules(object): + """ + :ivar _from: + :ivar to: + :ivar metadata: + """ + + def __init__(self, payload: Dict[str, Any]): + + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.metadata: Optional[Dict[str, str]] = payload.get("metadata") + + def to_dict(self): + return { + "from": self._from, + "to": self.to, + "metadata": self.metadata, + } + + class UpdateConfigurationRequestChannelSettingsValueStatusTimeouts(object): + """ + :ivar inactive: + :ivar closed: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.inactive: Optional[int] = payload.get("inactive") + self.closed: Optional[int] = payload.get("closed") + + def to_dict(self): + return { + "inactive": self.inactive, + "closed": self.closed, + } + + class UpdateConfigurationRequestStatusCallbacks(object): + """ + :ivar url: + :ivar method: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Configurations" + + def _create( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: The created ConfigurationInstance + """ + payload, _, _ = self._create( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + return ConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronously create the ConfigurationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: The created ConfigurationInstance + """ + payload, _, _ = await self._create_async( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + return ConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + idempotency_key: Union[str, object] = values.unset, + create_configuration_request: Union[ + CreateConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConfigurationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + :param create_configuration_request: The configuration to create + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + idempotency_key=idempotency_key, + create_configuration_request=create_configuration_request, + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfigurationInstance]: + """ + Streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfigurationInstance]: + """ + Asynchronously streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + memory_store_id=memory_store_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Lists ConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Asynchronously lists ConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfigurationInstance and returns headers from first page + + + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param str memory_store_id: Filter configurations by Memory Store ID + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + memory_store_id=memory_store_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "memoryStoreId": memory_store_id, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + memory_store_id: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Asynchronously retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "memoryStoreId": memory_store_id, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + memory_store_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "memoryStoreId": memory_store_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfigurationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + memory_store_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param memory_store_id: Filter configurations by Memory Store ID + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "memoryStoreId": memory_store_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConfigurationPage: + """ + Retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConfigurationPage: + """ + Asynchronously retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfigurationPage(self._version, response) + + def get(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: + """ + return ConfigurationContext(self._version, id=id) + + def __call__(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: + """ + return ConfigurationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/conversation.py b/twilio/rest/conversations/v2/conversation.py new file mode 100644 index 0000000000..43a44569ba --- /dev/null +++ b/twilio/rest/conversations/v2/conversation.py @@ -0,0 +1,1632 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationInstance(InstanceResource): + + class ConversationsV2Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + + class ConversationsV2ConversationGroupingType(object): + GROUP_BY_PROFILE = "GROUP_BY_PROFILE" + GROUP_BY_PARTICIPANT_ADDRESSES = "GROUP_BY_PARTICIPANT_ADDRESSES" + GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE = ( + "GROUP_BY_PARTICIPANT_ADDRESSES_AND_CHANNEL_TYPE" + ) + + class ConversationsV2ConversationStatus(object): + ACTIVE = "ACTIVE" + INACTIVE = "INACTIVE" + CLOSED = "CLOSED" + + class ConversationsV2ParticipantType(object): + HUMAN_AGENT = "HUMAN_AGENT" + CUSTOMER = "CUSTOMER" + AI_AGENT = "AI_AGENT" + AGENT = "AGENT" + UNKNOWN = "UNKNOWN" + + """ + :ivar id: Conversation ID. + :ivar account_id: Account ID. + :ivar configuration_id: Configuration ID. + :ivar status: + :ivar name: Conversation name. + :ivar created_at: Timestamp when this Conversation was created. + :ivar updated_at: Timestamp when this Conversation was last updated. + :ivar configuration: + :ivar participants: Participants in this Conversation. + :ivar status_url: URL to poll for operation status. + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.configuration_id: Optional[str] = payload.get("configurationId") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.name: Optional[str] = payload.get("name") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.configuration: Optional[str] = payload.get("configuration") + self.participants: Optional[List[str]] = payload.get("participants") + self.status_url: Optional[str] = payload.get("statusUrl") + self.related: Optional[Dict[str, str]] = payload.get("related") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + idempotency_key=idempotency_key, + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + idempotency_key=idempotency_key, + ) + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + idempotency_key=idempotency_key, + ) + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + idempotency_key=idempotency_key, + ) + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + return self._proxy.patch( + patch_conversation_by_id_request=patch_conversation_by_id_request, + ) + + async def patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + return await self._proxy.patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request, + ) + + def update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + async def update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + def update_with_http_info( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + async def update_with_http_info_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_conversation_by_id_request=update_conversation_by_id_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Conversations/{id}".format(**self._solution) + + def _delete(self, idempotency_key: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self, idempotency_key: Union[str, object] = values.unset) -> bool: + """ + Deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(idempotency_key=idempotency_key) + return success + + def delete_with_http_info( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the ConversationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(idempotency_key=idempotency_key) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Idempotency-Key": idempotency_key, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(idempotency_key=idempotency_key) + return success + + async def delete_with_http_info_async( + self, idempotency_key: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance and return response metadata + + :param idempotency_key: Client-generated UUID key to ensure idempotent behavior. Submitting the same key returns the original response without creating a duplicate operation. Keys are scoped to account + region with a 24-hour TTL. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + idempotency_key=idempotency_key + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + payload, _, _ = self._patch( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, id=self._solution["id"]) + + def patch_with_http_info( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Patch the ConversationInstance and return response metadata + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + instance = ConversationInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to patch the ConversationInstance + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: The patched ConversationInstance + """ + payload, _, _ = await self._patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, id=self._solution["id"]) + + async def patch_with_http_info_async( + self, + patch_conversation_by_id_request: Union[ + PatchConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ConversationInstance and return response metadata + + :param patch_conversation_by_id_request: The conversation fields to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + patch_conversation_by_id_request=patch_conversation_by_id_request + ) + instance = ConversationInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + payload, _, _ = self._update( + update_conversation_by_id_request=update_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_conversation_by_id_request=update_conversation_by_id_request + ) + instance = ConversationInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_conversation_by_id_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param update_conversation_by_id_request: The conversation to update + + :returns: The updated ConversationInstance + """ + payload, _, _ = await self._update_async( + update_conversation_by_id_request=update_conversation_by_id_request + ) + return ConversationInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + update_conversation_by_id_request: Union[ + UpdateConversationByIdRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance and return response metadata + + :param update_conversation_by_id_request: The conversation to update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_conversation_by_id_request=update_conversation_by_id_request + ) + instance = ConversationInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + class ConversationsV2Address(object): + """ + :ivar channel: + :ivar address: The address value formatted according to channel type: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") - CHAT: Customer-defined string identifier + :ivar channel_id: Channel-specific ID for correlating Communications. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional[ConversationsV2Channel] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel.to_dict() if self.channel is not None else None, + "address": self.address, + "channelId": self.channel_id, + } + + class ConversationsV2ConversationsV1Bridge(object): + """ + :ivar service_id: The Conversations V1 Service SID (IS prefix). One configuration per V1 Service SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.service_id: Optional[str] = payload.get("serviceId") + + def to_dict(self): + return { + "serviceId": self.service_id, + } + + class ConversationsV2StatusCallbackConfig(object): + """ + :ivar url: Destination URL for webhooks. + :ivar method: HTTP method used to invoke the webhook URL. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["ConversationInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + class CreateConversationWithConfigRequest(object): + """ + :ivar configuration_id: The ID of an existing configuration. + :ivar name: The name of the conversation. + :ivar configuration: + :ivar participants: Optional list of Participants to create with the Conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_id: Optional[str] = payload.get("configurationId") + self.name: Optional[str] = payload.get("name") + self.configuration: Optional[ + ConversationList.CreateConversationWithConfigRequestConfiguration + ] = payload.get("configuration") + self.participants: Optional[ + List[ConversationList.CreateConversationWithConfigRequestParticipants] + ] = payload.get("participants") + + def to_dict(self): + return { + "configurationId": self.configuration_id, + "name": self.name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "participants": ( + [participants.to_dict() for participants in self.participants] + if self.participants is not None + else None + ), + } + + class CreateConversationWithConfigRequestConfiguration(object): + """ + :ivar intelligence_configuration_ids: A list of Conversational Intelligence configuration IDs. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + + def to_dict(self): + return { + "intelligenceConfigurationIds": self.intelligence_configuration_ids, + } + + class CreateConversationWithConfigRequestParticipants(object): + """ + :ivar name: Display name for the Participant. + :ivar type: Type of Participant in the Conversation. + :ivar profile_id: Resolved profile ID. + :ivar addresses: List of Communication addresses for the Participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ConversationInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ + ConversationList.CreateConversationWithConfigRequestParticipantsAddresses + ] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + class CreateConversationWithConfigRequestParticipantsAddresses(object): + """ + :ivar channel: Channel type for a Communication address. + :ivar address: + :ivar channel_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["ConversationInstance.str"] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel, + "address": self.address, + "channelId": self.channel_id, + } + + class PatchConversationByIdRequest(object): + """ + :ivar name: The name of the Conversation. + :ivar status: Lifecycle status of a Conversation. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.configuration: Optional[ + ConversationList.PatchConversationByIdRequestConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "name": self.name, + "status": self.status, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class PatchConversationByIdRequestConfiguration(object): + """ + :ivar status_callbacks: List of webhook configurations for this conversation. Send an empty array to clear all callbacks and stop webhook delivery. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.status_callbacks: Optional[ + List[ConversationList.ConversationsV2StatusCallbackConfig] + ] = payload.get("statusCallbacks") + + def to_dict(self): + return { + "statusCallbacks": ( + [ + status_callbacks.to_dict() + for status_callbacks in self.status_callbacks + ] + if self.status_callbacks is not None + else None + ), + } + + class UpdateConversationByIdRequest(object): + """ + :ivar name: The name of the Conversation. + :ivar status: Lifecycle status of a Conversation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status, + } + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def _create( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_with_config_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param create_conversation_with_config_request: + + :returns: The created ConversationInstance + """ + payload, _, _ = self._create( + create_conversation_with_config_request=create_conversation_with_config_request + ) + return ConversationInstance(self._version, payload) + + def create_with_http_info( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param create_conversation_with_config_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_conversation_with_config_request=create_conversation_with_config_request + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_conversation_with_config_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param create_conversation_with_config_request: + + :returns: The created ConversationInstance + """ + payload, _, _ = await self._create_async( + create_conversation_with_config_request=create_conversation_with_config_request + ) + return ConversationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + create_conversation_with_config_request: Union[ + CreateConversationWithConfigRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationInstance and return response metadata + + :param create_conversation_with_config_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_conversation_with_config_request=create_conversation_with_config_request + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + channel_id=channel_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param List[str] status: Filters for specific statuses + :param str channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param str page_token: A URL-safe, base64-encoded token representing the page of results to return + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + channel_id=channel_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :returns: Page of ConversationInstance + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_size: Maximum number of items to return in a single response + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :returns: Page of ConversationInstance + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[List[str], object] = values.unset, + channel_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Filters for specific statuses + :param channel_id: The resource identifier (such as callSid or messageSid) to filter conversations. + :param page_token: A URL-safe, base64-encoded token representing the page of results to return + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "status": serialize.map(status, lambda e: e), + "channelId": channel_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: + """ + return ConversationContext(self._version, id=id) + + def __call__(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: + """ + return ConversationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/operation.py b/twilio/rest/conversations/v2/operation.py new file mode 100644 index 0000000000..9eaad7cd4c --- /dev/null +++ b/twilio/rest/conversations/v2/operation.py @@ -0,0 +1,280 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperationInstance(InstanceResource): + + class ConversationsV2OperationStatusValue(object): + PENDING = "PENDING" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + """ + :ivar operation_id: Unique identifier for the long-running operation. + :ivar status: + :ivar created_at: Timestamp when the operation was created. + :ivar completed_at: Timestamp when the operation completed. Only present for completed or failed operations. + :ivar status_url: URL to poll for operation status. + :ivar error: + :ivar related: Named resource identifiers associated with this operation. Keys depend on the operation type: - config-create, config-update, config-delete: configurationId - conversation-delete: conversationId + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.error: Optional[str] = payload.get("error") + self.related: Optional[Dict[str, str]] = payload.get("related") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Operations/{id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param id: + """ + return OperationContext(self._version, id=id) + + def __call__(self, id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param id: + """ + return OperationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v2/participant.py b/twilio/rest/conversations/v2/participant.py new file mode 100644 index 0000000000..63daceda08 --- /dev/null +++ b/twilio/rest/conversations/v2/participant.py @@ -0,0 +1,1156 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Conversation Orchestrator + Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ParticipantInstance(InstanceResource): + + class ConversationsV2Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + + class ConversationsV2ParticipantType(object): + HUMAN_AGENT = "HUMAN_AGENT" + CUSTOMER = "CUSTOMER" + AI_AGENT = "AI_AGENT" + AGENT = "AGENT" + UNKNOWN = "UNKNOWN" + + """ + :ivar id: Participant ID. + :ivar conversation_id: Conversation ID. + :ivar account_id: Account ID. + :ivar name: Participant display name. + :ivar type: + :ivar profile_id: Profile ID. Note: This field is only resolved for `CUSTOMER` participant types, not for `HUMAN_AGENT` or `AI_AGENT` participants. + :ivar addresses: Communication addresses for this Participant. Address format varies by channel: - SMS/VOICE: E.164 phone number (such as \"+18005550100\") - EMAIL: Email address (such as \"user@example.com\") - WHATSAPP: Phone number with whatsapp prefix (such as \"whatsapp:+18005550100\") - RCS: Sender ID or phone number with rcs prefix (such as \"rcs:brand_acme_agent\" or \"rcs:+18005550100\") + :ivar created_at: Timestamp when this Participant was created. + :ivar updated_at: Timestamp when this Participant was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.account_id: Optional[str] = payload.get("accountId") + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[List[str]] = payload.get("addresses") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + + # Only set _solution if path params are provided (not None) + if conversation_id is not None or id is not None: + self._solution = { + "conversation_id": conversation_id, + "id": id, + } + + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + async def update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + def update_with_http_info( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + async def update_with_http_info_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_participant_in_conversation_request=update_participant_in_conversation_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, conversation_id: str, id: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param conversation_id: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + "id": id, + } + self._uri = "/Conversations/{conversation_id}/Participants/{id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_participant_in_conversation_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._update( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + def update_with_http_info( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance and return response metadata + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_participant_in_conversation_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param update_participant_in_conversation_request: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + + async def update_with_http_info_async( + self, + update_participant_in_conversation_request: Union[ + UpdateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param update_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_participant_in_conversation_request=update_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, + payload, + conversation_id=self._solution["conversation_id"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ParticipantPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + + return ParticipantInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + class CreateConversationWithConfigRequestParticipantsAddresses(object): + """ + :ivar channel: Channel type for a Communication address. + :ivar address: + :ivar channel_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["ConversationInstance.str"] = payload.get("channel") + self.address: Optional[str] = payload.get("address") + self.channel_id: Optional[str] = payload.get("channelId") + + def to_dict(self): + return { + "channel": self.channel, + "address": self.address, + "channelId": self.channel_id, + } + + class CreateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: Type of Participant in the Conversation. + :ivar profile_id: + :ivar addresses: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ + ParticipantList.CreateConversationWithConfigRequestParticipantsAddresses + ] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + class UpdateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: Type of Participant in the Conversation. + :ivar profile_id: + :ivar addresses: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.type: Optional["ParticipantInstance.str"] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.addresses: Optional[ + List[ + ParticipantList.CreateConversationWithConfigRequestParticipantsAddresses + ] + ] = payload.get("addresses") + + def to_dict(self): + return { + "name": self.name, + "type": self.type, + "profileId": self.profile_id, + "addresses": ( + [addresses.to_dict() for addresses in self.addresses] + if self.addresses is not None + else None + ), + } + + def __init__(self, version: Version, conversation_id: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_id: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_id": conversation_id, + } + self._uri = "/Conversations/{conversation_id}/Participants".format( + **self._solution + ) + + def _create( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_participant_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + def create_with_http_info( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_participant_in_conversation_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param create_participant_in_conversation_request: + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + return ParticipantInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + + async def create_with_http_info_async( + self, + create_participant_in_conversation_request: Union[ + CreateParticipantInConversationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param create_participant_in_conversation_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_participant_in_conversation_request=create_participant_in_conversation_request + ) + instance = ParticipantInstance( + self._version, payload, conversation_id=self._solution["conversation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param str page_token: Page token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_size: Maximum number of items to return + :param page_token: Page token for pagination + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Page token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, solution=self._solution) + + def get(self, id: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param id: + """ + return ParticipantContext( + self._version, conversation_id=self._solution["conversation_id"], id=id + ) + + def __call__(self, id: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param id: + """ + return ParticipantContext( + self._version, conversation_id=self._solution["conversation_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/events/v1/event_type.py b/twilio/rest/events/v1/event_type.py index 7eaaeb03ba..d00ce94b1a 100644 --- a/twilio/rest/events/v1/event_type.py +++ b/twilio/rest/events/v1/event_type.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "type": type or self.type, } + self._context: Optional[EventTypeContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "EventTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,48 +139,96 @@ def __init__(self, version: Version, type: str): } self._uri = "/Types/{type}".format(**self._solution) - def fetch(self) -> EventTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the EventTypeInstance - + Internal helper for fetch operation - :returns: The fetched EventTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EventTypeInstance: + """ + Fetch the EventTypeInstance + + :returns: The fetched EventTypeInstance + """ + payload, _, _ = self._fetch() return EventTypeInstance( self._version, payload, type=self._solution["type"], ) - async def fetch_async(self) -> EventTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EventTypeInstance + Fetch the EventTypeInstance and return response metadata - :returns: The fetched EventTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EventTypeInstance: + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + payload, _, _ = await self._fetch_async() return EventTypeInstance( self._version, payload, type=self._solution["type"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -179,6 +247,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventTypeInstance: :param payload: Payload response from the API """ + return EventTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -257,6 +326,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventTypeInstance and returns headers from first page + + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + schema_id=schema_id, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventTypeInstance and returns headers from first page + + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + schema_id=schema_id, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, schema_id: Union[str, object] = values.unset, @@ -278,6 +403,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( schema_id=schema_id, @@ -307,6 +433,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -316,6 +443,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventTypeInstance and returns headers from first page + + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventTypeInstance and returns headers from first page + + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, schema_id: Union[str, object] = values.unset, @@ -388,6 +571,82 @@ async def page_async( ) return EventTypePage(self._version, response) + def page_with_http_info( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventTypePage, status code, and headers + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventTypePage, status code, and headers + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EventTypePage: """ Retrieve a specific page of EventTypeInstance records from the API. diff --git a/twilio/rest/events/v1/schema/__init__.py b/twilio/rest/events/v1/schema/__init__.py index 2c7ffa6b28..5d26d6f6ab 100644 --- a/twilio/rest/events/v1/schema/__init__.py +++ b/twilio/rest/events/v1/schema/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ def __init__( self._solution = { "id": id or self.id, } + self._context: Optional[SchemaContext] = None @property @@ -85,6 +87,24 @@ async def fetch_async(self) -> "SchemaInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def versions(self) -> SchemaVersionList: """ @@ -121,48 +141,96 @@ def __init__(self, version: Version, id: str): self._versions: Optional[SchemaVersionList] = None - def fetch(self) -> SchemaInstance: + def _fetch(self) -> tuple: """ - Fetch the SchemaInstance + Internal helper for fetch operation - - :returns: The fetched SchemaInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SchemaInstance: + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + payload, _, _ = self._fetch() return SchemaInstance( self._version, payload, id=self._solution["id"], ) - async def fetch_async(self) -> SchemaInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SchemaInstance + Fetch the SchemaInstance and return response metadata - :returns: The fetched SchemaInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SchemaInstance: + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + payload, _, _ = await self._fetch_async() return SchemaInstance( self._version, payload, id=self._solution["id"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def versions(self) -> SchemaVersionList: """ diff --git a/twilio/rest/events/v1/schema/schema_version.py b/twilio/rest/events/v1/schema/schema_version.py index be000b9c0b..d846590c83 100644 --- a/twilio/rest/events/v1/schema/schema_version.py +++ b/twilio/rest/events/v1/schema/schema_version.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "id": id, "schema_version": schema_version or self.schema_version, } + self._context: Optional[SchemaVersionContext] = None @property @@ -90,6 +92,24 @@ async def fetch_async(self) -> "SchemaVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,20 +139,30 @@ def __init__(self, version: Version, id: str, schema_version: int): } self._uri = "/Schemas/{id}/Versions/{schema_version}".format(**self._solution) - def fetch(self) -> SchemaVersionInstance: + def _fetch(self) -> tuple: """ - Fetch the SchemaVersionInstance - + Internal helper for fetch operation - :returns: The fetched SchemaVersionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SchemaVersionInstance: + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + payload, _, _ = self._fetch() return SchemaVersionInstance( self._version, payload, @@ -140,22 +170,46 @@ def fetch(self) -> SchemaVersionInstance: schema_version=self._solution["schema_version"], ) - async def fetch_async(self) -> SchemaVersionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SchemaVersionInstance + Fetch the SchemaVersionInstance and return response metadata - :returns: The fetched SchemaVersionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SchemaVersionInstance: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + payload, _, _ = await self._fetch_async() return SchemaVersionInstance( self._version, payload, @@ -163,6 +217,22 @@ async def fetch_async(self) -> SchemaVersionInstance: schema_version=self._solution["schema_version"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +251,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SchemaVersionInstance: :param payload: Payload response from the API """ + return SchemaVersionInstance(self._version, payload, id=self._solution["id"]) def __repr__(self) -> str: @@ -260,6 +331,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -279,6 +400,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -305,6 +427,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -313,6 +436,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SchemaVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -344,7 +517,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SchemaVersionPage(self._version, response, self._solution) + return SchemaVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -377,7 +550,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SchemaVersionPage(self._version, response, self._solution) + return SchemaVersionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SchemaVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SchemaVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SchemaVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SchemaVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SchemaVersionPage: """ @@ -389,7 +632,7 @@ def get_page(self, target_url: str) -> SchemaVersionPage: :returns: Page of SchemaVersionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SchemaVersionPage(self._version, response, self._solution) + return SchemaVersionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SchemaVersionPage: """ @@ -401,7 +644,7 @@ async def get_page_async(self, target_url: str) -> SchemaVersionPage: :returns: Page of SchemaVersionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SchemaVersionPage(self._version, response, self._solution) + return SchemaVersionPage(self._version, response, solution=self._solution) def get(self, schema_version: int) -> SchemaVersionContext: """ diff --git a/twilio/rest/events/v1/sink/__init__.py b/twilio/rest/events/v1/sink/__init__.py index 886c2947f5..6bed98c16b 100644 --- a/twilio/rest/events/v1/sink/__init__.py +++ b/twilio/rest/events/v1/sink/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,6 +31,7 @@ class SinkType(object): KINESIS = "kinesis" WEBHOOK = "webhook" SEGMENT = "segment" + EMAIL = "email" class Status(object): INITIALIZED = "initialized" @@ -73,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SinkContext] = None @property @@ -108,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SinkInstance": """ Fetch the SinkInstance @@ -126,6 +147,24 @@ async def fetch_async(self) -> "SinkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, description: str) -> "SinkInstance": """ Update the SinkInstance @@ -150,6 +189,30 @@ async def update_async(self, description: str) -> "SinkInstance": description=description, ) + def update_with_http_info(self, description: str) -> ApiResponse: + """ + Update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async(self, description: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) + @property def sink_test(self) -> SinkTestList: """ @@ -194,6 +257,20 @@ def __init__(self, version: Version, sid: str): self._sink_test: Optional[SinkTestList] = None self._sink_validate: Optional[SinkValidateList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SinkInstance @@ -201,10 +278,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SinkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -213,62 +312,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SinkInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SinkInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SinkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SinkInstance: + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + payload, _, _ = self._fetch() return SinkInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SinkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SinkInstance + Fetch the SinkInstance and return response metadata - :returns: The fetched SinkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SinkInstance: + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + payload, _, _ = await self._fetch_async() return SinkInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, description: str) -> SinkInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SinkInstance + Asynchronous coroutine to fetch the SinkInstance and return response metadata - :param description: A human readable description for the Sink **This value should not contain PII.** - :returns: The updated SinkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -282,19 +434,39 @@ def update(self, description: str) -> SinkInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, description: str) -> SinkInstance: + """ + Update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + payload, _, _ = self._update(description=description) return SinkInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async(self, description: str) -> SinkInstance: + def update_with_http_info(self, description: str) -> ApiResponse: """ - Asynchronous coroutine to update the SinkInstance + Update the SinkInstance and return response metadata :param description: A human readable description for the Sink **This value should not contain PII.** - :returns: The updated SinkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = SinkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, description: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,12 +480,35 @@ async def update_async(self, description: str) -> SinkInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, description: str) -> SinkInstance: + """ + Asynchronous coroutine to update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + payload, _, _ = await self._update_async(description=description) return SinkInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async(self, description: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = SinkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def sink_test(self) -> SinkTestList: """ @@ -356,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SinkInstance: :param payload: Payload response from the API """ + return SinkInstance(self._version, payload) def __repr__(self) -> str: @@ -380,20 +576,17 @@ def __init__(self, version: Version): self._uri = "/Sinks" - def create( + def _create( self, description: str, sink_configuration: object, sink_type: "SinkInstance.SinkType", - ) -> SinkInstance: + ) -> tuple: """ - Create the SinkInstance - - :param description: A human readable description for the Sink **This value should not contain PII.** - :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. - :param sink_type: + Internal helper for create operation - :returns: The created SinkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -409,20 +602,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SinkInstance(self._version, payload) - - async def create_async( + def create( self, description: str, sink_configuration: object, sink_type: "SinkInstance.SinkType", ) -> SinkInstance: """ - Asynchronously create the SinkInstance + Create the SinkInstance :param description: A human readable description for the Sink **This value should not contain PII.** :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. @@ -430,6 +621,48 @@ async def create_async( :returns: The created SinkInstance """ + payload, _, _ = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + return SinkInstance(self._version, payload) + + def create_with_http_info( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Create the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -444,12 +677,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Asynchronously create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + payload, _, _ = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) return SinkInstance(self._version, payload) + async def create_with_http_info_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Asynchronously create the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, in_use: Union[bool, object] = values.unset, @@ -510,6 +786,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SinkInstance and returns headers from first page + + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SinkInstance and returns headers from first page + + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, in_use: Union[bool, object] = values.unset, @@ -533,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( in_use=in_use, @@ -565,6 +902,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -575,6 +913,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SinkInstance and returns headers from first page + + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SinkInstance and returns headers from first page + + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, in_use: Union[bool, object] = values.unset, @@ -653,6 +1053,88 @@ async def page_async( ) return SinkPage(self._version, response) + def page_with_http_info( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SinkPage, status code, and headers + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SinkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SinkPage, status code, and headers + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SinkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SinkPage: """ Retrieve a specific page of SinkInstance records from the API. diff --git a/twilio/rest/events/v1/sink/sink_test.py b/twilio/rest/events/v1/sink/sink_test.py index 566106efca..7d253b7536 100644 --- a/twilio/rest/events/v1/sink/sink_test.py +++ b/twilio/rest/events/v1/sink/sink_test.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,40 +63,80 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Sinks/{sid}/Test".format(**self._solution) - def create(self) -> SinkTestInstance: + def _create(self) -> tuple: """ - Create the SinkTestInstance + Internal helper for create operation - - :returns: The created SinkTestInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.create(method="POST", uri=self._uri, headers=headers) + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> SinkTestInstance: + """ + Create the SinkTestInstance + + :returns: The created SinkTestInstance + """ + payload, _, _ = self._create() return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) - async def create_async(self) -> SinkTestInstance: + def create_with_http_info(self) -> ApiResponse: """ - Asynchronously create the SinkTestInstance + Create the SinkTestInstance and return response metadata - :returns: The created SinkTestInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, headers=headers ) + async def create_async(self) -> SinkTestInstance: + """ + Asynchronously create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + payload, _, _ = await self._create_async() return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the SinkTestInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/events/v1/sink/sink_validate.py b/twilio/rest/events/v1/sink/sink_validate.py index 53eef814c0..aa7a169673 100644 --- a/twilio/rest/events/v1/sink/sink_validate.py +++ b/twilio/rest/events/v1/sink/sink_validate.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,13 +63,12 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Sinks/{sid}/Validate".format(**self._solution) - def create(self, test_id: str) -> SinkValidateInstance: + def _create(self, test_id: str) -> tuple: """ - Create the SinkValidateInstance + Internal helper for create operation - :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. - - :returns: The created SinkValidateInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -82,19 +82,41 @@ def create(self, test_id: str) -> SinkValidateInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, test_id: str) -> SinkValidateInstance: + """ + Create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + payload, _, _ = self._create(test_id=test_id) return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) - async def create_async(self, test_id: str) -> SinkValidateInstance: + def create_with_http_info(self, test_id: str) -> ApiResponse: """ - Asynchronously create the SinkValidateInstance + Create the SinkValidateInstance and return response metadata :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. - :returns: The created SinkValidateInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(test_id=test_id) + instance = SinkValidateInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, test_id: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -108,12 +130,35 @@ async def create_async(self, test_id: str) -> SinkValidateInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, test_id: str) -> SinkValidateInstance: + """ + Asynchronously create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + payload, _, _ = await self._create_async(test_id=test_id) return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + async def create_with_http_info_async(self, test_id: str) -> ApiResponse: + """ + Asynchronously create the SinkValidateInstance and return response metadata + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(test_id=test_id) + instance = SinkValidateInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/events/v1/subscription/__init__.py b/twilio/rest/events/v1/subscription/__init__.py index 872c9ed7d0..f494c773c9 100644 --- a/twilio/rest/events/v1/subscription/__init__.py +++ b/twilio/rest/events/v1/subscription/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SubscriptionContext] = None @property @@ -91,6 +93,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SubscriptionInstance": """ Fetch the SubscriptionInstance @@ -109,40 +129,78 @@ async def fetch_async(self) -> "SubscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, + self, description: Union[str, object] = values.unset ) -> "SubscriptionInstance": """ Update the SubscriptionInstance :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. :returns: The updated SubscriptionInstance """ return self._proxy.update( description=description, - sink_sid=sink_sid, ) async def update_async( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, + self, description: Union[str, object] = values.unset ) -> "SubscriptionInstance": """ Asynchronous coroutine to update the SubscriptionInstance :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. :returns: The updated SubscriptionInstance """ return await self._proxy.update_async( description=description, - sink_sid=sink_sid, + ) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, ) @property @@ -181,6 +239,20 @@ def __init__(self, version: Version, sid: str): self._subscribed_events: Optional[SubscribedEventList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SubscriptionInstance @@ -188,10 +260,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -200,73 +294,120 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SubscriptionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SubscriptionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SubscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscriptionInstance: + """ + Fetch the SubscriptionInstance + + :returns: The fetched SubscriptionInstance + """ + payload, _, _ = self._fetch() return SubscriptionInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SubscriptionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SubscriptionInstance + Fetch the SubscriptionInstance and return response metadata - :returns: The fetched SubscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SubscriptionInstance: + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + payload, _, _ = await self._fetch_async() return SubscriptionInstance( self._version, payload, sid=self._solution["sid"], ) - def update( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, - ) -> SubscriptionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SubscriptionInstance + Asynchronous coroutine to fetch the SubscriptionInstance and return response metadata - :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. - :returns: The updated SubscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { "Description": description, - "SinkSid": sink_sid, } ) headers = values.of({}) @@ -275,30 +416,52 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, + def update( + self, description: Union[str, object] = values.unset ) -> SubscriptionInstance: """ - Asynchronous coroutine to update the SubscriptionInstance + Update the SubscriptionInstance :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. :returns: The updated SubscriptionInstance """ + payload, _, _ = self._update(description=description) + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = SubscriptionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { "Description": description, - "SinkSid": sink_sid, } ) headers = values.of({}) @@ -307,12 +470,41 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, description: Union[str, object] = values.unset + ) -> SubscriptionInstance: + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + + :returns: The updated SubscriptionInstance + """ + payload, _, _ = await self._update_async(description=description) return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = SubscriptionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def subscribed_events(self) -> SubscribedEventList: """ @@ -343,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscriptionInstance: :param payload: Payload response from the API """ + return SubscriptionInstance(self._version, payload) def __repr__(self) -> str: @@ -367,17 +560,12 @@ def __init__(self, version: Version): self._uri = "/Subscriptions" - def create( - self, description: str, sink_sid: str, types: List[object] - ) -> SubscriptionInstance: + def _create(self, description: str, sink_sid: str, types: List[object]) -> tuple: """ - Create the SubscriptionInstance - - :param description: A human readable description for the Subscription **This value should not contain PII.** - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. - :param types: An array of objects containing the subscribed Event Types + Internal helper for create operation - :returns: The created SubscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,17 +581,15 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SubscriptionInstance(self._version, payload) - - async def create_async( + def create( self, description: str, sink_sid: str, types: List[object] ) -> SubscriptionInstance: """ - Asynchronously create the SubscriptionInstance + Create the SubscriptionInstance :param description: A human readable description for the Subscription **This value should not contain PII.** :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. @@ -411,6 +597,38 @@ async def create_async( :returns: The created SubscriptionInstance """ + payload, _, _ = self._create( + description=description, sink_sid=sink_sid, types=types + ) + return SubscriptionInstance(self._version, payload) + + def create_with_http_info( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Create the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -425,12 +643,45 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Asynchronously create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + payload, _, _ = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) return SubscriptionInstance(self._version, payload) + async def create_with_http_info_async( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Asynchronously create the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sink_sid: Union[str, object] = values.unset, @@ -485,6 +736,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscriptionInstance and returns headers from first page + + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sink_sid=sink_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscriptionInstance and returns headers from first page + + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sink_sid=sink_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sink_sid: Union[str, object] = values.unset, @@ -506,6 +813,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sink_sid=sink_sid, @@ -535,6 +843,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -544,6 +853,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscriptionInstance and returns headers from first page + + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscriptionInstance and returns headers from first page + + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sink_sid: Union[str, object] = values.unset, @@ -616,6 +981,82 @@ async def page_async( ) return SubscriptionPage(self._version, response) + def page_with_http_info( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscriptionPage, status code, and headers + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscriptionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscriptionPage, status code, and headers + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscriptionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SubscriptionPage: """ Retrieve a specific page of SubscriptionInstance records from the API. diff --git a/twilio/rest/events/v1/subscription/subscribed_event.py b/twilio/rest/events/v1/subscription/subscribed_event.py index dae60ac206..7ad59f767b 100644 --- a/twilio/rest/events/v1/subscription/subscribed_event.py +++ b/twilio/rest/events/v1/subscription/subscribed_event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "subscription_sid": subscription_sid, "type": type or self.type, } + self._context: Optional[SubscribedEventContext] = None @property @@ -87,6 +89,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SubscribedEventInstance": """ Fetch the SubscribedEventInstance @@ -105,6 +125,24 @@ async def fetch_async(self) -> "SubscribedEventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, schema_version: Union[int, object] = values.unset ) -> "SubscribedEventInstance": @@ -133,6 +171,34 @@ async def update_async( schema_version=schema_version, ) + def update_with_http_info( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + schema_version=schema_version, + ) + + async def update_with_http_info_async( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + schema_version=schema_version, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,6 +230,20 @@ def __init__(self, version: Version, subscription_sid: str, type: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SubscribedEventInstance @@ -171,10 +251,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscribedEventInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -183,27 +285,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SubscribedEventInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SubscribedEventInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SubscribedEventInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribedEventInstance: + """ + Fetch the SubscribedEventInstance + + :returns: The fetched SubscribedEventInstance + """ + payload, _, _ = self._fetch() return SubscribedEventInstance( self._version, payload, @@ -211,22 +329,46 @@ def fetch(self) -> SubscribedEventInstance: type=self._solution["type"], ) - async def fetch_async(self) -> SubscribedEventInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SubscribedEventInstance + Fetch the SubscribedEventInstance and return response metadata - :returns: The fetched SubscribedEventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SubscribedEventInstance: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + payload, _, _ = await self._fetch_async() return SubscribedEventInstance( self._version, payload, @@ -234,15 +376,28 @@ async def fetch_async(self) -> SubscribedEventInstance: type=self._solution["type"], ) - def update( - self, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SubscribedEventInstance + Asynchronous coroutine to fetch the SubscribedEventInstance and return response metadata - :param schema_version: The schema version that the Subscription should use. - :returns: The updated SubscribedEventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, schema_version: Union[int, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -256,10 +411,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + payload, _, _ = self._update(schema_version=schema_version) return SubscribedEventInstance( self._version, payload, @@ -267,15 +433,33 @@ def update( type=self._solution["type"], ) - async def update_async( + def update_with_http_info( self, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SubscribedEventInstance + Update the SubscribedEventInstance and return response metadata :param schema_version: The schema version that the Subscription should use. - :returns: The updated SubscribedEventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(schema_version=schema_version) + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, schema_version: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -289,10 +473,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronous coroutine to update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + payload, _, _ = await self._update_async(schema_version=schema_version) return SubscribedEventInstance( self._version, payload, @@ -300,6 +495,27 @@ async def update_async( type=self._solution["type"], ) + async def update_with_http_info_async( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscribedEventInstance and return response metadata + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -318,6 +534,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscribedEventInstance: :param payload: Payload response from the API """ + return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) @@ -351,16 +568,14 @@ def __init__(self, version: Version, subscription_sid: str): **self._solution ) - def create( + def _create( self, type: str, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + ) -> tuple: """ - Create the SubscribedEventInstance - - :param type: Type of event being subscribed to. - :param schema_version: The schema version that the Subscription should use. + Internal helper for create operation - :returns: The created SubscribedEventInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -375,24 +590,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + payload, _, _ = self._create(type=type, schema_version=schema_version) return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) - async def create_async( + def create_with_http_info( self, type: str, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + ) -> ApiResponse: """ - Asynchronously create the SubscribedEventInstance + Create the SubscribedEventInstance and return response metadata :param type: Type of event being subscribed to. :param schema_version: The schema version that the Subscription should use. - :returns: The created SubscribedEventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -407,14 +651,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronously create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + payload, _, _ = await self._create_async( + type=type, schema_version=schema_version + ) return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) + async def create_with_http_info_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the SubscribedEventInstance and return response metadata + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -465,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -484,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -510,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -518,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscribedEventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -549,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SubscribedEventPage(self._version, response, self._solution) + return SubscribedEventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -582,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SubscribedEventPage(self._version, response, self._solution) + return SubscribedEventPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedEventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscribedEventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedEventPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscribedEventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SubscribedEventPage: """ @@ -594,7 +1043,7 @@ def get_page(self, target_url: str) -> SubscribedEventPage: :returns: Page of SubscribedEventInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SubscribedEventPage(self._version, response, self._solution) + return SubscribedEventPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SubscribedEventPage: """ @@ -606,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> SubscribedEventPage: :returns: Page of SubscribedEventInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SubscribedEventPage(self._version, response, self._solution) + return SubscribedEventPage(self._version, response, solution=self._solution) def get(self, type: str) -> SubscribedEventContext: """ diff --git a/twilio/rest/flex_api/v1/assessments.py b/twilio/rest/flex_api/v1/assessments.py index 130514b295..003b309a89 100644 --- a/twilio/rest/flex_api/v1/assessments.py +++ b/twilio/rest/flex_api/v1/assessments.py @@ -13,7 +13,8 @@ """ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values +from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,9 +50,9 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.assessment_sid: Optional[str] = payload.get("assessment_sid") - self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.offset: Optional[str] = payload.get("offset") self.report: Optional[bool] = payload.get("report") - self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.weight: Optional[str] = payload.get("weight") self.agent_id: Optional[str] = payload.get("agent_id") self.segment_id: Optional[str] = payload.get("segment_id") self.user_name: Optional[str] = payload.get("user_name") @@ -59,12 +60,13 @@ def __init__( self.answer_text: Optional[str] = payload.get("answer_text") self.answer_id: Optional[str] = payload.get("answer_id") self.assessment: Optional[Dict[str, object]] = payload.get("assessment") - self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.timestamp: Optional[str] = payload.get("timestamp") self.url: Optional[str] = payload.get("url") self._solution = { "assessment_sid": assessment_sid or self.assessment_sid, } + self._context: Optional[AssessmentsContext] = None @property @@ -130,6 +132,54 @@ async def update_async( authorization=authorization, ) + def update_with_http_info( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AssessmentsInstance with HTTP info + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssessmentsInstance with HTTP info + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,22 +209,18 @@ def __init__(self, version: Version, assessment_sid: str): **self._solution ) - def update( + def _update( self, offset: float, answer_text: str, answer_id: str, authorization: Union[str, object] = values.unset, - ) -> AssessmentsInstance: + ) -> tuple: """ - Update the AssessmentsInstance - - :param offset: The offset of the conversation - :param answer_text: The answer text selected by user - :param answer_id: The id of the answer selected by user - :param authorization: The Authorization HTTP request header + Internal helper for update operation - :returns: The updated AssessmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -196,30 +242,77 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + payload, _, _ = self._update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) return AssessmentsInstance( self._version, payload, assessment_sid=self._solution["assessment_sid"] ) - async def update_async( + def update_with_http_info( self, offset: float, answer_text: str, answer_id: str, authorization: Union[str, object] = values.unset, - ) -> AssessmentsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AssessmentsInstance + Update the AssessmentsInstance and return response metadata :param offset: The offset of the conversation :param answer_text: The answer text selected by user :param answer_id: The id of the answer selected by user :param authorization: The Authorization HTTP request header - :returns: The updated AssessmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + instance = AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -241,14 +334,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronous coroutine to update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + payload, _, _ = await self._update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) return AssessmentsInstance( self._version, payload, assessment_sid=self._solution["assessment_sid"] ) + async def update_with_http_info_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssessmentsInstance and return response metadata + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + instance = AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -267,6 +411,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssessmentsInstance: :param payload: Payload response from the API """ + return AssessmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -291,7 +436,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Assessments" - def create( + def _create( self, category_sid: str, category_name: str, @@ -304,23 +449,12 @@ def create( answer_id: str, questionnaire_sid: str, authorization: Union[str, object] = values.unset, - ) -> AssessmentsInstance: + ) -> tuple: """ - Create the AssessmentsInstance + Internal helper for create operation - :param category_sid: The SID of the category - :param category_name: The name of the category - :param segment_id: Segment Id of the conversation - :param agent_id: The id of the Agent - :param offset: The offset of the conversation. - :param metric_id: The question SID selected for assessment - :param metric_name: The question name of the assessment - :param answer_text: The answer text selected by user - :param answer_id: The id of the answer selected by user - :param questionnaire_sid: Questionnaire SID of the associated question - :param authorization: The Authorization HTTP request header - - :returns: The created AssessmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -348,13 +482,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AssessmentsInstance(self._version, payload) - - async def create_async( + def create( self, category_sid: str, category_name: str, @@ -369,7 +501,7 @@ async def create_async( authorization: Union[str, object] = values.unset, ) -> AssessmentsInstance: """ - Asynchronously create the AssessmentsInstance + Create the AssessmentsInstance :param category_sid: The SID of the category :param category_name: The name of the category @@ -385,6 +517,88 @@ async def create_async( :returns: The created AssessmentsInstance """ + payload, _, _ = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + return AssessmentsInstance(self._version, payload) + + def create_with_http_info( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AssessmentsInstance and return response metadata + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + instance = AssessmentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -411,12 +625,103 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronously create the AssessmentsInstance + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: The created AssessmentsInstance + """ + payload, _, _ = await self._create_async( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) return AssessmentsInstance(self._version, payload) + async def create_with_http_info_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AssessmentsInstance and return response metadata + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + instance = AssessmentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, authorization: Union[str, object] = values.unset, @@ -483,6 +788,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -506,6 +875,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -538,6 +908,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -548,6 +919,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -636,6 +1069,98 @@ async def page_async( ) return AssessmentsPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssessmentsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssessmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssessmentsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssessmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AssessmentsPage: """ Retrieve a specific page of AssessmentsInstance records from the API. diff --git a/twilio/rest/flex_api/v1/channel.py b/twilio/rest/flex_api/v1/channel.py index aa98ff8d31..0f223bc426 100644 --- a/twilio/rest/flex_api/v1/channel.py +++ b/twilio/rest/flex_api/v1/channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -135,6 +173,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Channels/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -142,10 +194,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -154,55 +228,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() return ChannelInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelInstance + Fetch the ChannelInstance and return response metadata - :returns: The fetched ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() return ChannelInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -221,6 +349,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -245,7 +374,7 @@ def __init__(self, version: Version): self._uri = "/Channels" - def create( + def _create( self, flex_flow_sid: str, identity: str, @@ -257,22 +386,12 @@ def create( task_sid: Union[str, object] = values.unset, task_attributes: Union[str, object] = values.unset, long_lived: Union[bool, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param flex_flow_sid: The SID of the Flex Flow. - :param identity: The `identity` value that uniquely identifies the new resource's chat User. - :param chat_user_friendly_name: The chat participant's friendly name. - :param chat_friendly_name: The chat channel's friendly name. - :param target: The Target Contact Identity, for example the phone number of an SMS. - :param chat_unique_name: The chat channel's unique name. - :param pre_engagement_data: The pre-engagement data. - :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` - :param task_attributes: The Task attributes to be added for the TaskRouter Task. - :param long_lived: Whether to create the channel as long-lived. - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,13 +414,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ChannelInstance(self._version, payload) - - async def create_async( + def create( self, flex_flow_sid: str, identity: str, @@ -315,7 +432,7 @@ async def create_async( long_lived: Union[bool, object] = values.unset, ) -> ChannelInstance: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance :param flex_flow_sid: The SID of the Flex Flow. :param identity: The `identity` value that uniquely identifies the new resource's chat User. @@ -330,6 +447,83 @@ async def create_async( :returns: The created ChannelInstance """ + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + return ChannelInstance(self._version, payload) + + def create_with_http_info( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +545,97 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) return ChannelInstance(self._version, payload) + async def create_with_http_info_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -407,6 +686,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -426,6 +755,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -452,6 +782,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -460,6 +791,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -526,6 +907,76 @@ async def page_async( ) return ChannelPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ChannelPage: """ Retrieve a specific page of ChannelInstance records from the API. diff --git a/twilio/rest/flex_api/v1/configuration.py b/twilio/rest/flex_api/v1/configuration.py index 28a66be036..6e8f586a01 100644 --- a/twilio/rest/flex_api/v1/configuration.py +++ b/twilio/rest/flex_api/v1/configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -237,6 +238,34 @@ async def fetch_async( ui_version=ui_version, ) + def fetch_with_http_info( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + ui_version=ui_version, + ) + + async def fetch_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + ui_version=ui_version, + ) + def update( self, body: Union[object, object] = values.unset ) -> "ConfigurationInstance": @@ -265,6 +294,34 @@ async def update_async( body=body, ) + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -287,18 +344,15 @@ def __init__(self, version: Version): self._uri = "/Configuration" - def fetch( - self, ui_version: Union[str, object] = values.unset - ) -> ConfigurationInstance: + def _fetch(self, ui_version: Union[str, object] = values.unset) -> tuple: """ - Fetch the ConfigurationInstance + Internal helper for fetch operation - :param ui_version: The Pinned UI version of the Configuration resource to fetch. - - :returns: The fetched ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "UiVersion": ui_version, } @@ -308,27 +362,54 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch(ui_version=ui_version) return ConfigurationInstance( self._version, payload, ) - async def fetch_async( + def fetch_with_http_info( self, ui_version: Union[str, object] = values.unset - ) -> ConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConfigurationInstance + Fetch the ConfigurationInstance and return response metadata :param ui_version: The Pinned UI version of the Configuration resource to fetch. - :returns: The fetched ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(ui_version=ui_version) + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "UiVersion": ui_version, } @@ -338,24 +419,49 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async(ui_version=ui_version) return ConfigurationInstance( self._version, payload, ) - def update( - self, body: Union[object, object] = values.unset - ) -> ConfigurationInstance: + async def fetch_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - Update the ConfigurationInstance + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata - :param body: + :param ui_version: The Pinned UI version of the Configuration resource to fetch. - :returns: The updated ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(ui_version=ui_version) + instance = ConfigurationInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -365,22 +471,44 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConfigurationInstance(self._version, payload) - - async def update_async( + def update( self, body: Union[object, object] = values.unset ) -> ConfigurationInstance: """ - Asynchronous coroutine to update the ConfigurationInstance + Update the ConfigurationInstance :param body: :returns: The updated ConfigurationInstance """ + payload, _, _ = self._update(body=body) + return ConfigurationInstance(self._version, payload) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = body.to_dict() headers = values.of({}) @@ -389,12 +517,37 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async(body=body) return ConfigurationInstance(self._version, payload) + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(body=body) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/flex_flow.py b/twilio/rest/flex_api/v1/flex_flow.py index 0ae2634666..35f61b0683 100644 --- a/twilio/rest/flex_api/v1/flex_flow.py +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlexFlowContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlexFlowInstance": """ Fetch the FlexFlowInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "FlexFlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -268,6 +306,136 @@ async def update_async( integration_retry_count=integration_retry_count, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexFlowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexFlowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -295,6 +463,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/FlexFlows/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlexFlowInstance @@ -302,10 +484,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlexFlowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -314,56 +518,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlexFlowInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> FlexFlowInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the FlexFlowInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched FlexFlowInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlexFlowInstance: + """ + Fetch the FlexFlowInstance + + :returns: The fetched FlexFlowInstance + """ + payload, _, _ = self._fetch() return FlexFlowInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> FlexFlowInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlexFlowInstance + Fetch the FlexFlowInstance and return response metadata - :returns: The fetched FlexFlowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlexFlowInstance: + """ + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + payload, _, _ = await self._fetch_async() return FlexFlowInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexFlowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, chat_service_sid: Union[str, object] = values.unset, @@ -384,29 +642,12 @@ def update( long_lived: Union[bool, object] = values.unset, janitor_enabled: Union[bool, object] = values.unset, integration_retry_count: Union[int, object] = values.unset, - ) -> FlexFlowInstance: + ) -> tuple: """ - Update the FlexFlowInstance - - :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. - :param chat_service_sid: The SID of the chat service. - :param channel_type: - :param contact_identity: The channel contact's Identity. - :param enabled: Whether the new Flex Flow is enabled. - :param integration_type: - :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. - :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. - :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. - :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. - :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. - :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. - :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. - :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. - :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. - :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. - :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + Internal helper for update operation - :returns: The updated FlexFlowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -438,13 +679,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, chat_service_sid: Union[str, object] = values.unset, @@ -467,7 +706,7 @@ async def update_async( integration_retry_count: Union[int, object] = values.unset, ) -> FlexFlowInstance: """ - Asynchronous coroutine to update the FlexFlowInstance + Update the FlexFlowInstance :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. :param chat_service_sid: The SID of the chat service. @@ -489,11 +728,127 @@ async def update_async( :returns: The updated FlexFlowInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexFlowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + instance = FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, "ChannelType": channel_type, "ContactIdentity": contact_identity, "Enabled": serialize.boolean_to_string(enabled), @@ -519,12 +874,143 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexFlowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + instance = FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -543,6 +1029,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: :param payload: Payload response from the API """ + return FlexFlowInstance(self._version, payload) def __repr__(self) -> str: @@ -562,12 +1049,269 @@ def __init__(self, version: Version): :param version: Version that contains the resource - """ - super().__init__(version) + """ + super().__init__(version) + + self._uri = "/FlexFlows" + + def _create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + return FlexFlowInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the FlexFlowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + instance = FlexFlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - self._uri = "/FlexFlows" + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def create( + async def create_async( self, friendly_name: str, chat_service_sid: str, @@ -590,7 +1334,7 @@ def create( integration_retry_count: Union[int, object] = values.unset, ) -> FlexFlowInstance: """ - Create the FlexFlowInstance + Asynchronously create the FlexFlowInstance :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. :param chat_service_sid: The SID of the chat service. @@ -612,43 +1356,28 @@ def create( :returns: The created FlexFlowInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, - "ChannelType": channel_type, - "ContactIdentity": contact_identity, - "Enabled": serialize.boolean_to_string(enabled), - "IntegrationType": integration_type, - "Integration.FlowSid": integration_flow_sid, - "Integration.Url": integration_url, - "Integration.WorkspaceSid": integration_workspace_sid, - "Integration.WorkflowSid": integration_workflow_sid, - "Integration.Channel": integration_channel, - "Integration.Timeout": integration_timeout, - "Integration.Priority": integration_priority, - "Integration.CreationOnMessage": serialize.boolean_to_string( - integration_creation_on_message - ), - "LongLived": serialize.boolean_to_string(long_lived), - "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), - "Integration.RetryCount": integration_retry_count, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, ) - return FlexFlowInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, friendly_name: str, chat_service_sid: str, @@ -669,9 +1398,9 @@ async def create_async( long_lived: Union[bool, object] = values.unset, janitor_enabled: Union[bool, object] = values.unset, integration_retry_count: Union[int, object] = values.unset, - ) -> FlexFlowInstance: + ) -> ApiResponse: """ - Asynchronously create the FlexFlowInstance + Asynchronously create the FlexFlowInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. :param chat_service_sid: The SID of the chat service. @@ -691,43 +1420,29 @@ async def create_async( :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. - :returns: The created FlexFlowInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, - "ChannelType": channel_type, - "ContactIdentity": contact_identity, - "Enabled": serialize.boolean_to_string(enabled), - "IntegrationType": integration_type, - "Integration.FlowSid": integration_flow_sid, - "Integration.Url": integration_url, - "Integration.WorkspaceSid": integration_workspace_sid, - "Integration.WorkflowSid": integration_workflow_sid, - "Integration.Channel": integration_channel, - "Integration.Timeout": integration_timeout, - "Integration.Priority": integration_priority, - "Integration.CreationOnMessage": serialize.boolean_to_string( - integration_creation_on_message - ), - "LongLived": serialize.boolean_to_string(long_lived), - "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), - "Integration.RetryCount": integration_retry_count, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, ) - - return FlexFlowInstance(self._version, payload) + instance = FlexFlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -785,6 +1500,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FlexFlowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FlexFlowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -806,6 +1577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -835,6 +1607,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -844,6 +1617,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FlexFlowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FlexFlowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -916,6 +1745,82 @@ async def page_async( ) return FlexFlowPage(self._version, response) + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlexFlowPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlexFlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlexFlowPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlexFlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> FlexFlowPage: """ Retrieve a specific page of FlexFlowInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_assessments_comment.py b/twilio/rest/flex_api/v1/insights_assessments_comment.py index 2b6c79343b..0f48ce1cc5 100644 --- a/twilio/rest/flex_api/v1/insights_assessments_comment.py +++ b/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -13,7 +13,8 @@ """ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values +from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -43,14 +44,14 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.account_sid: Optional[str] = payload.get("account_sid") self.assessment_sid: Optional[str] = payload.get("assessment_sid") self.comment: Optional[Dict[str, object]] = payload.get("comment") - self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.offset: Optional[str] = payload.get("offset") self.report: Optional[bool] = payload.get("report") - self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.weight: Optional[str] = payload.get("weight") self.agent_id: Optional[str] = payload.get("agent_id") self.segment_id: Optional[str] = payload.get("segment_id") self.user_name: Optional[str] = payload.get("user_name") self.user_email: Optional[str] = payload.get("user_email") - self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.timestamp: Optional[str] = payload.get("timestamp") self.url: Optional[str] = payload.get("url") def __repr__(self) -> str: @@ -73,6 +74,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsAssessmentsCommentInstance(self._version, payload) def __repr__(self) -> str: @@ -97,7 +99,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Assessments/Comments" - def create( + def _create( self, category_id: str, category_name: str, @@ -106,19 +108,12 @@ def create( agent_id: str, offset: float, authorization: Union[str, object] = values.unset, - ) -> InsightsAssessmentsCommentInstance: + ) -> tuple: """ - Create the InsightsAssessmentsCommentInstance + Internal helper for create operation - :param category_id: The ID of the category - :param category_name: The name of the category - :param comment: The Assessment comment. - :param segment_id: The id of the segment. - :param agent_id: The id of the agent. - :param offset: The offset - :param authorization: The Authorization HTTP request header - - :returns: The created InsightsAssessmentsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -142,13 +137,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InsightsAssessmentsCommentInstance(self._version, payload) - - async def create_async( + def create( self, category_id: str, category_name: str, @@ -159,7 +152,7 @@ async def create_async( authorization: Union[str, object] = values.unset, ) -> InsightsAssessmentsCommentInstance: """ - Asynchronously create the InsightsAssessmentsCommentInstance + Create the InsightsAssessmentsCommentInstance :param category_id: The ID of the category :param category_name: The name of the category @@ -171,6 +164,68 @@ async def create_async( :returns: The created InsightsAssessmentsCommentInstance """ + payload, _, _ = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + return InsightsAssessmentsCommentInstance(self._version, payload) + + def create_with_http_info( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsAssessmentsCommentInstance and return response metadata + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + instance = InsightsAssessmentsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -193,12 +248,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> InsightsAssessmentsCommentInstance: + """ + Asynchronously create the InsightsAssessmentsCommentInstance + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsAssessmentsCommentInstance + """ + payload, _, _ = await self._create_async( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) return InsightsAssessmentsCommentInstance(self._version, payload) + async def create_with_http_info_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InsightsAssessmentsCommentInstance and return response metadata + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + instance = InsightsAssessmentsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, authorization: Union[str, object] = values.unset, @@ -271,6 +393,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -296,6 +488,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -331,6 +524,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -342,6 +536,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -436,6 +698,104 @@ async def page_async( ) return InsightsAssessmentsCommentPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsAssessmentsCommentPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsAssessmentsCommentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsAssessmentsCommentPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsAssessmentsCommentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsAssessmentsCommentPage: """ Retrieve a specific page of InsightsAssessmentsCommentInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_conversations.py b/twilio/rest/flex_api/v1/insights_conversations.py index efdcea203e..c407089755 100644 --- a/twilio/rest/flex_api/v1/insights_conversations.py +++ b/twilio/rest/flex_api/v1/insights_conversations.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsConversationsInstance :param payload: Payload response from the API """ + return InsightsConversationsInstance(self._version, payload) def __repr__(self) -> str: @@ -147,6 +149,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -170,6 +236,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -202,6 +269,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -212,6 +280,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -300,6 +430,98 @@ async def page_async( ) return InsightsConversationsPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsConversationsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsConversationsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsConversationsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsConversationsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsConversationsPage: """ Retrieve a specific page of InsightsConversationsInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_questionnaires.py b/twilio/rest/flex_api/v1/insights_questionnaires.py index d21aff8242..3ecf2f8156 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "questionnaire_sid": questionnaire_sid or self.questionnaire_sid, } + self._context: Optional[InsightsQuestionnairesContext] = None @property @@ -94,6 +96,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def fetch( self, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesInstance": @@ -122,6 +152,34 @@ async def fetch_async( authorization=authorization, ) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + authorization=authorization, + ) + def update( self, active: bool, @@ -176,6 +234,60 @@ async def update_async( question_sids=question_sids, ) + def update_with_http_info( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesInstance with HTTP info + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + async def update_with_http_info_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance with HTTP info + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +319,25 @@ def __init__(self, version: Version, questionnaire_sid: str): ) ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesInstance @@ -215,6 +346,31 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -223,7 +379,9 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, authorization: Union[str, object] = values.unset @@ -235,16 +393,44 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "Authorization": authorization, - } + success, _, _ = await self._delete_async(authorization=authorization) + return success + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({}) - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch( @@ -257,26 +443,54 @@ def fetch( :returns: The fetched InsightsQuestionnairesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = self._fetch(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param authorization: The Authorization HTTP request header - return InsightsQuestionnairesInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsQuestionnairesInstance( self._version, payload, questionnaire_sid=self._solution["questionnaire_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, authorization: Union[str, object] = values.unset @@ -288,45 +502,46 @@ async def fetch_async( :returns: The fetched InsightsQuestionnairesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance and return response metadata - headers["Accept"] = "application/json" + :param authorization: The Authorization HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization ) - - return InsightsQuestionnairesInstance( + instance = InsightsQuestionnairesInstance( self._version, payload, questionnaire_sid=self._solution["questionnaire_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update( + def _update( self, active: bool, authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> tuple: """ - Update the InsightsQuestionnairesInstance - - :param active: The flag to enable or disable questionnaire - :param authorization: The Authorization HTTP request header - :param name: The name of this questionnaire - :param description: The description of this questionnaire - :param question_sids: The list of questions sids under a questionnaire + Internal helper for update operation - :returns: The updated InsightsQuestionnairesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -349,26 +564,52 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + payload, _, _ = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) return InsightsQuestionnairesInstance( self._version, payload, questionnaire_sid=self._solution["questionnaire_sid"], ) - async def update_async( + def update_with_http_info( self, active: bool, authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InsightsQuestionnairesInstance + Update the InsightsQuestionnairesInstance and return response metadata :param active: The flag to enable or disable questionnaire :param authorization: The Authorization HTTP request header @@ -376,7 +617,35 @@ async def update_async( :param description: The description of this questionnaire :param question_sids: The list of questions sids under a questionnaire - :returns: The updated InsightsQuestionnairesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -399,20 +668,79 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return InsightsQuestionnairesInstance( - self._version, - payload, - questionnaire_sid=self._solution["questionnaire_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - + async def update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + payload, _, _ = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def update_with_http_info_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance and return response metadata + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) @@ -427,6 +755,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsQuestionnairesInstanc :param payload: Payload response from the API """ + return InsightsQuestionnairesInstance(self._version, payload) def __repr__(self) -> str: @@ -451,24 +780,19 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Questionnaires" - def create( + def _create( self, name: str, authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, active: Union[bool, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesInstance + Internal helper for create operation - :param name: The name of this questionnaire - :param authorization: The Authorization HTTP request header - :param description: The description of this questionnaire - :param active: The flag to enable or disable questionnaire - :param question_sids: The list of questions sids under a questionnaire - - :returns: The created InsightsQuestionnairesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -490,13 +814,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InsightsQuestionnairesInstance(self._version, payload) - - async def create_async( + def create( self, name: str, authorization: Union[str, object] = values.unset, @@ -505,7 +827,7 @@ async def create_async( question_sids: Union[List[str], object] = values.unset, ) -> InsightsQuestionnairesInstance: """ - Asynchronously create the InsightsQuestionnairesInstance + Create the InsightsQuestionnairesInstance :param name: The name of this questionnaire :param authorization: The Authorization HTTP request header @@ -515,6 +837,58 @@ async def create_async( :returns: The created InsightsQuestionnairesInstance """ + payload, _, _ = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance(self._version, payload) + + def create_with_http_info( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesInstance and return response metadata + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -535,12 +909,67 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronously create the InsightsQuestionnairesInstance + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The created InsightsQuestionnairesInstance + """ + payload, _, _ = await self._create_async( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) return InsightsQuestionnairesInstance(self._version, payload) + async def create_with_http_info_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesInstance and return response metadata + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, authorization: Union[str, object] = values.unset, @@ -607,6 +1036,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -630,6 +1123,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -662,6 +1156,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -672,6 +1167,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -760,6 +1317,98 @@ async def page_async( ) return InsightsQuestionnairesPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesPage: """ Retrieve a specific page of InsightsQuestionnairesInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_category.py b/twilio/rest/flex_api/v1/insights_questionnaires_category.py index 817a4753f9..9cc42e866a 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_category.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__( self._solution = { "category_sid": category_sid or self.category_sid, } + self._context: Optional[InsightsQuestionnairesCategoryContext] = None @property @@ -88,6 +90,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def update( self, name: str, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesCategoryInstance": @@ -120,6 +150,38 @@ async def update_async( authorization=authorization, ) + def update_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + name=name, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + name=name, + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -151,6 +213,25 @@ def __init__(self, version: Version, category_sid: str): **self._solution ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesCategoryInstance @@ -159,6 +240,31 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -167,7 +273,9 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, authorization: Union[str, object] = values.unset @@ -179,28 +287,32 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "Authorization": authorization, - } - ) + success, _, _ = await self._delete_async(authorization=authorization) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def update( + def _update( self, name: str, authorization: Union[str, object] = values.unset - ) -> InsightsQuestionnairesCategoryInstance: + ) -> tuple: """ - Update the InsightsQuestionnairesCategoryInstance + Internal helper for update operation - :param name: The name of this category. - :param authorization: The Authorization HTTP request header - - :returns: The updated InsightsQuestionnairesCategoryInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -220,24 +332,53 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + payload, _, _ = self._update(name=name, authorization=authorization) return InsightsQuestionnairesCategoryInstance( self._version, payload, category_sid=self._solution["category_sid"] ) - async def update_async( + def update_with_http_info( self, name: str, authorization: Union[str, object] = values.unset - ) -> InsightsQuestionnairesCategoryInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + Update the InsightsQuestionnairesCategoryInstance and return response metadata :param name: The name of this category. :param authorization: The Authorization HTTP request header - :returns: The updated InsightsQuestionnairesCategoryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -257,14 +398,45 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + payload, _, _ = await self._update_async(name=name, authorization=authorization) return InsightsQuestionnairesCategoryInstance( self._version, payload, category_sid=self._solution["category_sid"] ) + async def update_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -287,6 +459,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesCategoryInstance(self._version, payload) def __repr__(self) -> str: @@ -311,16 +484,14 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Categories" - def create( + def _create( self, name: str, authorization: Union[str, object] = values.unset - ) -> InsightsQuestionnairesCategoryInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesCategoryInstance + Internal helper for create operation - :param name: The name of this category. - :param authorization: The Authorization HTTP request header - - :returns: The created InsightsQuestionnairesCategoryInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -339,23 +510,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InsightsQuestionnairesCategoryInstance(self._version, payload) - - async def create_async( + def create( self, name: str, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesCategoryInstance: """ - Asynchronously create the InsightsQuestionnairesCategoryInstance + Create the InsightsQuestionnairesCategoryInstance :param name: The name of this category. :param authorization: The Authorization HTTP request header :returns: The created InsightsQuestionnairesCategoryInstance """ + payload, _, _ = self._create(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def create_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -373,12 +571,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronously create the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsQuestionnairesCategoryInstance + """ + payload, _, _ = await self._create_async(name=name, authorization=authorization) return InsightsQuestionnairesCategoryInstance(self._version, payload) + async def create_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, authorization: Union[str, object] = values.unset, @@ -435,6 +662,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -456,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -485,6 +769,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -494,6 +779,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -576,6 +917,92 @@ async def page_async( ) return InsightsQuestionnairesCategoryPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesCategoryPage: """ Retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_question.py b/twilio/rest/flex_api/v1/insights_questionnaires_question.py index 33e2304599..e8a88190b6 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_question.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "question_sid": question_sid or self.question_sid, } + self._context: Optional[InsightsQuestionnairesQuestionContext] = None @property @@ -100,6 +102,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def update( self, allow_na: bool, @@ -160,6 +190,66 @@ async def update_async( answer_set_id=answer_set_id, ) + def update_with_http_info( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesQuestionInstance with HTTP info + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + async def update_with_http_info_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance with HTTP info + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -191,6 +281,25 @@ def __init__(self, version: Version, question_sid: str): **self._solution ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesQuestionInstance @@ -199,6 +308,31 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -207,7 +341,9 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, authorization: Union[str, object] = values.unset @@ -219,19 +355,25 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "Authorization": authorization, - } - ) + success, _, _ = await self._delete_async(authorization=authorization) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - def update( + def _update( self, allow_na: bool, authorization: Union[str, object] = values.unset, @@ -239,18 +381,12 @@ def update( question: Union[str, object] = values.unset, description: Union[str, object] = values.unset, answer_set_id: Union[str, object] = values.unset, - ) -> InsightsQuestionnairesQuestionInstance: + ) -> tuple: """ - Update the InsightsQuestionnairesQuestionInstance + Internal helper for update operation - :param allow_na: The flag to enable for disable NA for answer. - :param authorization: The Authorization HTTP request header - :param category_sid: The SID of the category - :param question: The question. - :param description: The description for the question. - :param answer_set_id: The answer_set for the question. - - :returns: The updated InsightsQuestionnairesQuestionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -274,15 +410,44 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + payload, _, _ = self._update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) return InsightsQuestionnairesQuestionInstance( self._version, payload, question_sid=self._solution["question_sid"] ) - async def update_async( + def update_with_http_info( self, allow_na: bool, authorization: Union[str, object] = values.unset, @@ -290,9 +455,9 @@ async def update_async( question: Union[str, object] = values.unset, description: Union[str, object] = values.unset, answer_set_id: Union[str, object] = values.unset, - ) -> InsightsQuestionnairesQuestionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + Update the InsightsQuestionnairesQuestionInstance and return response metadata :param allow_na: The flag to enable for disable NA for answer. :param authorization: The Authorization HTTP request header @@ -301,7 +466,35 @@ async def update_async( :param description: The description for the question. :param answer_set_id: The answer_set for the question. - :returns: The updated InsightsQuestionnairesQuestionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + instance = InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -325,14 +518,77 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + payload, _, _ = await self._update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) return InsightsQuestionnairesQuestionInstance( self._version, payload, question_sid=self._solution["question_sid"] ) + async def update_with_http_info_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance and return response metadata + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + instance = InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -355,6 +611,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesQuestionInstance(self._version, payload) def __repr__(self) -> str: @@ -379,7 +636,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Questions" - def create( + def _create( self, category_sid: str, question: str, @@ -387,18 +644,12 @@ def create( allow_na: bool, authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> InsightsQuestionnairesQuestionInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesQuestionInstance - - :param category_sid: The SID of the category - :param question: The question. - :param answer_set_id: The answer_set for the question. - :param allow_na: The flag to enable for disable NA for answer. - :param authorization: The Authorization HTTP request header - :param description: The description for the question. + Internal helper for create operation - :returns: The created InsightsQuestionnairesQuestionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -421,13 +672,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InsightsQuestionnairesQuestionInstance(self._version, payload) - - async def create_async( + def create( self, category_sid: str, question: str, @@ -437,7 +686,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> InsightsQuestionnairesQuestionInstance: """ - Asynchronously create the InsightsQuestionnairesQuestionInstance + Create the InsightsQuestionnairesQuestionInstance :param category_sid: The SID of the category :param question: The question. @@ -448,10 +697,67 @@ async def create_async( :returns: The created InsightsQuestionnairesQuestionInstance """ + payload, _, _ = self._create( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + return InsightsQuestionnairesQuestionInstance(self._version, payload) - data = values.of( - { - "CategorySid": category_sid, + def create_with_http_info( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesQuestionInstance and return response metadata + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + instance = InsightsQuestionnairesQuestionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "CategorySid": category_sid, "Question": question, "AnswerSetId": answer_set_id, "AllowNa": serialize.boolean_to_string(allow_na), @@ -469,12 +775,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronously create the InsightsQuestionnairesQuestionInstance + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: The created InsightsQuestionnairesQuestionInstance + """ + payload, _, _ = await self._create_async( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) return InsightsQuestionnairesQuestionInstance(self._version, payload) + async def create_with_http_info_async( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InsightsQuestionnairesQuestionInstance and return response metadata + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + instance = InsightsQuestionnairesQuestionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, authorization: Union[str, object] = values.unset, @@ -541,6 +908,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -564,6 +995,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -596,6 +1028,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -606,6 +1039,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -694,6 +1189,98 @@ async def page_async( ) return InsightsQuestionnairesQuestionPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesQuestionPage: """ Retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_segments.py b/twilio/rest/flex_api/v1/insights_segments.py index 7c98e81cff..e5232a323a 100644 --- a/twilio/rest/flex_api/v1/insights_segments.py +++ b/twilio/rest/flex_api/v1/insights_segments.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsSegmentsInstance: :param payload: Payload response from the API """ + return InsightsSegmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -197,6 +199,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -222,6 +294,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -257,6 +330,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -268,6 +342,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -362,6 +504,104 @@ async def page_async( ) return InsightsSegmentsPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsSegmentsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsSegmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsSegmentsPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsSegmentsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsSegmentsPage: """ Retrieve a specific page of InsightsSegmentsInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_session.py b/twilio/rest/flex_api/v1/insights_session.py index b4174aa949..d633933625 100644 --- a/twilio/rest/flex_api/v1/insights_session.py +++ b/twilio/rest/flex_api/v1/insights_session.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,34 @@ async def create_async( authorization=authorization, ) + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + authorization=authorization, + ) + + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -104,6 +133,29 @@ def __init__(self, version: Version): self._uri = "/Insights/Session" + def _create(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, authorization: Union[str, object] = values.unset ) -> InsightsSessionInstance: @@ -114,15 +166,47 @@ def create( :returns: The created InsightsSessionInstance """ - data = values.of( - { - "Authorization": authorization, - } - ) + payload, _, _ = self._create(authorization=authorization) + return InsightsSessionInstance(self._version, payload) - payload = self._version.create(method="POST", uri=self._uri, data=data) + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance and return response metadata - return InsightsSessionInstance(self._version, payload) + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(authorization=authorization) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, authorization: Union[str, object] = values.unset @@ -134,17 +218,24 @@ async def create_async( :returns: The created InsightsSessionInstance """ - data = values.of( - { - "Authorization": authorization, - } - ) + payload, _, _ = await self._create_async(authorization=authorization) + return InsightsSessionInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance and return response metadata - return InsightsSessionInstance(self._version, payload) + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + authorization=authorization + ) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py index 9b0e89e938..8f6938ded8 100644 --- a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py +++ b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,14 +64,12 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Settings/AnswerSets" - def fetch( - self, authorization: Union[str, object] = values.unset - ) -> InsightsSettingsAnswerSetsInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsAnswerSetsInstance + Internal helper for fetch operation - :param authorization: The Authorization HTTP request header - :returns: The fetched InsightsSettingsAnswerSetsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of( { @@ -81,19 +80,44 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return InsightsSettingsAnswerSetsInstance(self._version, payload) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - async def fetch_async( + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsSettingsAnswerSetsInstance: """ - Asynchronously fetch the InsightsSettingsAnswerSetsInstance + Fetch the InsightsSettingsAnswerSetsInstance :param authorization: The Authorization HTTP request header :returns: The fetched InsightsSettingsAnswerSetsInstance """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsAnswerSetsInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsAnswerSetsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -103,12 +127,37 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + payload, _, _ = await self._fetch_async(authorization=authorization) return InsightsSettingsAnswerSetsInstance(self._version, payload) + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsSettingsAnswerSetsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/insights_settings_comment.py b/twilio/rest/flex_api/v1/insights_settings_comment.py index 18733a4957..44ca4f4d36 100644 --- a/twilio/rest/flex_api/v1/insights_settings_comment.py +++ b/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,14 +58,12 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Settings/CommentTags" - def fetch( - self, authorization: Union[str, object] = values.unset - ) -> InsightsSettingsCommentInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsCommentInstance + Internal helper for fetch operation - :param authorization: The Authorization HTTP request header - :returns: The fetched InsightsSettingsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of( { @@ -75,19 +74,44 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return InsightsSettingsCommentInstance(self._version, payload) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - async def fetch_async( + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsSettingsCommentInstance: """ - Asynchronously fetch the InsightsSettingsCommentInstance + Fetch the InsightsSettingsCommentInstance :param authorization: The Authorization HTTP request header :returns: The fetched InsightsSettingsCommentInstance """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsCommentInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsCommentInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -97,12 +121,37 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Asynchronously fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + payload, _, _ = await self._fetch_async(authorization=authorization) return InsightsSettingsCommentInstance(self._version, payload) + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the InsightsSettingsCommentInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization + ) + instance = InsightsSettingsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/insights_user_roles.py b/twilio/rest/flex_api/v1/insights_user_roles.py index 19cb10b8e4..33ef7c663a 100644 --- a/twilio/rest/flex_api/v1/insights_user_roles.py +++ b/twilio/rest/flex_api/v1/insights_user_roles.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,34 @@ async def fetch_async( authorization=authorization, ) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -98,6 +127,28 @@ def __init__(self, version: Version): self._uri = "/Insights/UserRoles" + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsUserRolesInstance: @@ -108,24 +159,51 @@ def fetch( :returns: The fetched InsightsUserRolesInstance """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsUserRolesInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance and return response metadata - data = values.of( - { - "Authorization": authorization, - } + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsUserRolesInstance( + self._version, + payload, ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({}) - headers["Accept"] = "application/json" + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + headers["Accept"] = "application/json" - return InsightsUserRolesInstance( - self._version, - payload, + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers ) async def fetch_async( @@ -138,25 +216,30 @@ async def fetch_async( :returns: The fetched InsightsUserRolesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsUserRolesInstance( + self._version, + payload, ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance and return response metadata - headers["Accept"] = "application/json" + :param authorization: The Authorization HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + authorization=authorization ) - - return InsightsUserRolesInstance( + instance = InsightsUserRolesInstance( self._version, payload, ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/interaction/__init__.py b/twilio/rest/flex_api/v1/interaction/__init__.py index c67d9c026e..9e63203161 100644 --- a/twilio/rest/flex_api/v1/interaction/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -32,6 +33,7 @@ class InteractionInstance(InstanceResource): :ivar url: :ivar links: :ivar interaction_context_sid: + :ivar webhook_ttid: """ def __init__( @@ -47,10 +49,12 @@ def __init__( self.interaction_context_sid: Optional[str] = payload.get( "interaction_context_sid" ) + self.webhook_ttid: Optional[str] = payload.get("webhook_ttid") self._solution = { "sid": sid or self.sid, } + self._context: Optional[InteractionContext] = None @property @@ -86,6 +90,80 @@ async def fetch_async(self) -> "InteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return self._proxy.update( + webhook_ttid=webhook_ttid, + ) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return await self._proxy.update_async( + webhook_ttid=webhook_ttid, + ) + + def update_with_http_info( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_ttid=webhook_ttid, + ) + + async def update_with_http_info_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + webhook_ttid=webhook_ttid, + ) + @property def channels(self) -> InteractionChannelList: """ @@ -122,48 +200,204 @@ def __init__(self, version: Version, sid: str): self._channels: Optional[InteractionChannelList] = None - def fetch(self) -> InteractionInstance: + def _fetch(self) -> tuple: """ - Fetch the InteractionInstance - + Internal helper for fetch operation - :returns: The fetched InteractionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + :returns: The fetched InteractionInstance + """ + payload, _, _ = self._fetch() return InteractionInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> InteractionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InteractionInstance + Fetch the InteractionInstance and return response metadata - :returns: The fetched InteractionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + payload, _, _ = await self._fetch_async() return InteractionInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, webhook_ttid: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + payload, _, _ = self._update(webhook_ttid=webhook_ttid) + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionInstance and return response metadata + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(webhook_ttid=webhook_ttid) + instance = InteractionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + payload, _, _ = await self._update_async(webhook_ttid=webhook_ttid) + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionInstance and return response metadata + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + webhook_ttid=webhook_ttid + ) + instance = InteractionInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def channels(self) -> InteractionChannelList: """ @@ -199,20 +433,18 @@ def __init__(self, version: Version): self._uri = "/Interactions" - def create( + def _create( self, channel: object, routing: Union[object, object] = values.unset, interaction_context_sid: Union[str, object] = values.unset, - ) -> InteractionInstance: + webhook_ttid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the InteractionInstance + Internal helper for create operation - :param channel: The Interaction's channel. - :param routing: The Interaction's routing logic. - :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid - - :returns: The created InteractionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -220,6 +452,7 @@ def create( "Channel": serialize.object(channel), "Routing": serialize.object(routing), "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -228,33 +461,81 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InteractionInstance(self._version, payload) - - async def create_async( + def create( self, channel: object, routing: Union[object, object] = values.unset, interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, ) -> InteractionInstance: """ - Asynchronously create the InteractionInstance + Create the InteractionInstance :param channel: The Interaction's channel. :param routing: The Interaction's routing logic. :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook :returns: The created InteractionInstance """ + payload, _, _ = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + return InteractionInstance(self._version, payload) + + def create_with_http_info( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InteractionInstance and return response metadata + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + instance = InteractionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { "Channel": serialize.object(channel), "Routing": serialize.object(routing), "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -263,12 +544,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> InteractionInstance: + """ + Asynchronously create the InteractionInstance + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The created InteractionInstance + """ + payload, _, _ = await self._create_async( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) return InteractionInstance(self._version, payload) + async def create_with_http_info_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InteractionInstance and return response metadata + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + instance = InteractionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> InteractionContext: """ Constructs a InteractionContext diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py index 781adb9797..2c362c9dbd 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,9 @@ from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_participant import ( InteractionChannelParticipantList, ) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_transfer import ( + InteractionTransferList, +) class InteractionChannelInstance(InstanceResource): @@ -35,6 +39,8 @@ class ChannelStatus(object): FAILED = "failed" CLOSED = "closed" INACTIVE = "inactive" + PAUSE = "pause" + TRANSFER = "transfer" class Type(object): VOICE = "voice" @@ -85,6 +91,7 @@ def __init__( "interaction_sid": interaction_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelContext] = None @property @@ -121,6 +128,24 @@ async def fetch_async(self) -> "InteractionChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "InteractionChannelInstance.UpdateChannelStatus", @@ -157,6 +182,42 @@ async def update_async( routing=routing, ) + def update_with_http_info( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the InteractionChannelInstance with HTTP info + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + routing=routing, + ) + + async def update_with_http_info_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelInstance with HTTP info + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + routing=routing, + ) + @property def invites(self) -> InteractionChannelInviteList: """ @@ -171,6 +232,13 @@ def participants(self) -> InteractionChannelParticipantList: """ return self._proxy.participants + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + return self._proxy.transfers + def __repr__(self) -> str: """ Provide a friendly representation @@ -204,21 +272,32 @@ def __init__(self, version: Version, interaction_sid: str, sid: str): self._invites: Optional[InteractionChannelInviteList] = None self._participants: Optional[InteractionChannelParticipantList] = None + self._transfers: Optional[InteractionTransferList] = None - def fetch(self) -> InteractionChannelInstance: + def _fetch(self) -> tuple: """ - Fetch the InteractionChannelInstance - + Internal helper for fetch operation - :returns: The fetched InteractionChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> InteractionChannelInstance: + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + payload, _, _ = self._fetch() return InteractionChannelInstance( self._version, payload, @@ -226,22 +305,46 @@ def fetch(self) -> InteractionChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InteractionChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InteractionChannelInstance + Fetch the InteractionChannelInstance and return response metadata - :returns: The fetched InteractionChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InteractionChannelInstance: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + payload, _, _ = await self._fetch_async() return InteractionChannelInstance( self._version, payload, @@ -249,18 +352,32 @@ async def fetch_async(self) -> InteractionChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, - ) -> InteractionChannelInstance: + ) -> tuple: """ - Update the InteractionChannelInstance + Internal helper for update operation - :param status: - :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. - - :returns: The updated InteractionChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -275,10 +392,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + payload, _, _ = self._update(status=status, routing=routing) return InteractionChannelInstance( self._version, payload, @@ -286,18 +417,38 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, - ) -> InteractionChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InteractionChannelInstance + Update the InteractionChannelInstance and return response metadata :param status: :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. - :returns: The updated InteractionChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status, routing=routing) + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -312,10 +463,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Asynchronous coroutine to update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + payload, _, _ = await self._update_async(status=status, routing=routing) return InteractionChannelInstance( self._version, payload, @@ -323,6 +488,30 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelInstance and return response metadata + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, routing=routing + ) + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def invites(self) -> InteractionChannelInviteList: """ @@ -349,6 +538,19 @@ def participants(self) -> InteractionChannelParticipantList: ) return self._participants + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + if self._transfers is None: + self._transfers = InteractionTransferList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._transfers + def __repr__(self) -> str: """ Provide a friendly representation @@ -367,6 +569,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInstance: :param payload: Payload response from the API """ + return InteractionChannelInstance( self._version, payload, interaction_sid=self._solution["interaction_sid"] ) @@ -448,6 +651,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -467,6 +720,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,6 +747,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -501,6 +756,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -532,7 +837,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionChannelPage(self._version, response, self._solution) + return InteractionChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -565,7 +870,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionChannelPage(self._version, response, self._solution) + return InteractionChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InteractionChannelPage: """ @@ -577,7 +952,7 @@ def get_page(self, target_url: str) -> InteractionChannelPage: :returns: Page of InteractionChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InteractionChannelPage(self._version, response, self._solution) + return InteractionChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InteractionChannelPage: """ @@ -589,7 +964,7 @@ async def get_page_async(self, target_url: str) -> InteractionChannelPage: :returns: Page of InteractionChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InteractionChannelPage(self._version, response, self._solution) + return InteractionChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> InteractionChannelContext: """ diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py index a81acd4fc4..b34035b6b2 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInviteInsta :param payload: Payload response from the API """ + return InteractionChannelInviteInstance( self._version, payload, @@ -108,13 +110,12 @@ def __init__(self, version: Version, interaction_sid: str, channel_sid: str): ) ) - def create(self, routing: object) -> InteractionChannelInviteInstance: + def _create(self, routing: object) -> tuple: """ - Create the InteractionChannelInviteInstance + Internal helper for create operation - :param routing: The Interaction's routing logic. - - :returns: The created InteractionChannelInviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -128,10 +129,19 @@ def create(self, routing: object) -> InteractionChannelInviteInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, routing: object) -> InteractionChannelInviteInstance: + """ + Create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + payload, _, _ = self._create(routing=routing) return InteractionChannelInviteInstance( self._version, payload, @@ -139,13 +149,29 @@ def create(self, routing: object) -> InteractionChannelInviteInstance: channel_sid=self._solution["channel_sid"], ) - async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + def create_with_http_info(self, routing: object) -> ApiResponse: """ - Asynchronously create the InteractionChannelInviteInstance + Create the InteractionChannelInviteInstance and return response metadata :param routing: The Interaction's routing logic. - :returns: The created InteractionChannelInviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(routing=routing) + instance = InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, routing: object) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -159,10 +185,19 @@ async def create_async(self, routing: object) -> InteractionChannelInviteInstanc headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + """ + Asynchronously create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + payload, _, _ = await self._create_async(routing=routing) return InteractionChannelInviteInstance( self._version, payload, @@ -170,6 +205,23 @@ async def create_async(self, routing: object) -> InteractionChannelInviteInstanc channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async(self, routing: object) -> ApiResponse: + """ + Asynchronously create the InteractionChannelInviteInstance and return response metadata + + :param routing: The Interaction's routing logic. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(routing=routing) + instance = InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -220,6 +272,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -239,6 +341,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -265,6 +368,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -273,6 +377,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelInviteInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -304,7 +458,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionChannelInvitePage(self._version, response, self._solution) + return InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -337,7 +493,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionChannelInvitePage(self._version, response, self._solution) + return InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InteractionChannelInvitePage: """ @@ -349,7 +581,9 @@ def get_page(self, target_url: str) -> InteractionChannelInvitePage: :returns: Page of InteractionChannelInviteInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InteractionChannelInvitePage(self._version, response, self._solution) + return InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> InteractionChannelInvitePage: """ @@ -361,7 +595,9 @@ async def get_page_async(self, target_url: str) -> InteractionChannelInvitePage: :returns: Page of InteractionChannelInviteInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InteractionChannelInvitePage(self._version, response, self._solution) + return InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py index 53d2d40dbf..9be568cea4 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelParticipantContext] = None @property @@ -116,6 +118,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -153,15 +183,12 @@ def __init__( **self._solution ) - def update( - self, status: "InteractionChannelParticipantInstance.Status" - ) -> InteractionChannelParticipantInstance: + def _update(self, status: "InteractionChannelParticipantInstance.Status") -> tuple: """ - Update the InteractionChannelParticipantInstance + Internal helper for update operation - :param status: - - :returns: The updated InteractionChannelParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -175,10 +202,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + payload, _, _ = self._update(status=status) return InteractionChannelParticipantInstance( self._version, payload, @@ -187,15 +225,34 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "InteractionChannelParticipantInstance.Status" - ) -> InteractionChannelParticipantInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InteractionChannelParticipantInstance + Update the InteractionChannelParticipantInstance and return response metadata :param status: - :returns: The updated InteractionChannelParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -209,10 +266,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + payload, _, _ = await self._update_async(status=status) return InteractionChannelParticipantInstance( self._version, payload, @@ -221,6 +289,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -243,6 +331,7 @@ def get_instance( :param payload: Payload response from the API """ + return InteractionChannelParticipantInstance( self._version, payload, @@ -281,20 +370,17 @@ def __init__(self, version: Version, interaction_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, routing_properties: Union[object, object] = values.unset, - ) -> InteractionChannelParticipantInstance: + ) -> tuple: """ - Create the InteractionChannelParticipantInstance + Internal helper for create operation - :param type: - :param media_properties: JSON representing the Media Properties for the new Participant. - :param routing_properties: Object representing the Routing Properties for the new Participant. - - :returns: The created InteractionChannelParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,10 +396,30 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + payload, _, _ = self._create( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) return InteractionChannelParticipantInstance( self._version, payload, @@ -321,20 +427,45 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, routing_properties: Union[object, object] = values.unset, - ) -> InteractionChannelParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the InteractionChannelParticipantInstance + Create the InteractionChannelParticipantInstance and return response metadata :param type: :param media_properties: JSON representing the Media Properties for the new Participant. :param routing_properties: Object representing the Routing Properties for the new Participant. - :returns: The created InteractionChannelParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -350,10 +481,30 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Asynchronously create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + payload, _, _ = await self._create_async( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) return InteractionChannelParticipantInstance( self._version, payload, @@ -361,6 +512,34 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InteractionChannelParticipantInstance and return response metadata + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -411,6 +590,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -430,6 +659,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -456,6 +686,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -464,6 +695,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionChannelParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -496,7 +777,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -531,8 +812,82 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelParticipantPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InteractionChannelParticipantPage: """ @@ -545,7 +900,7 @@ def get_page(self, target_url: str) -> InteractionChannelParticipantPage: """ response = self._version.domain.twilio.request("GET", target_url) return InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -561,7 +916,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> InteractionChannelParticipantContext: diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py new file mode 100644 index 0000000000..13f59fadbc --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py @@ -0,0 +1,633 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InteractionTransferInstance(InstanceResource): + + class TransferStatus(object): + ACTIVE = "active" + FAILED = "failed" + COMPLETED = "completed" + + class TransferType(object): + WARM = "warm" + COLD = "cold" + EXTERNAL = "external" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Transfer resource. + :ivar instance_sid: The SID of the Instance associated with the Transfer. + :ivar account_sid: The SID of the Account that created the Transfer. + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Transfer. + :ivar execution_sid: The Execution SID associated with the Transfer. + :ivar type: + :ivar status: + :ivar _from: The SID of the Participant initiating the Transfer. + :ivar to: The SID of the Participant receiving the Transfer. + :ivar note_sid: The SID of the Note associated with the Transfer. + :ivar summary_sid: The SID of the Summary associated with the Transfer. + :ivar date_created: The date and time when the Transfer was created. + :ivar date_updated: The date and time when the Transfer was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.type: Optional["InteractionTransferInstance.TransferType"] = payload.get( + "type" + ) + self.status: Optional["InteractionTransferInstance.TransferStatus"] = ( + payload.get("status") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.note_sid: Optional[str] = payload.get("note_sid") + self.summary_sid: Optional[str] = payload.get("summary_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + + self._context: Optional[InteractionTransferContext] = None + + @property + def _proxy(self) -> "InteractionTransferContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionTransferContext for this InteractionTransferInstance + """ + if self._context is None: + self._context = InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionTransferInstance": + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionTransferContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Transfer. + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionTransferInstance: + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = self._fetch() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InteractionTransferInstance: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = await self._fetch_async() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = self._update(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = await self._update_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionTransferList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for the Interaction + :param channel_sid: The Channel Sid for the Channel. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers".format( + **self._solution + ) + ) + + def _create(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = self._create(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronously create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = await self._create_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin/__init__.py b/twilio/rest/flex_api/v1/plugin/__init__.py index 2415c42710..5765f3478d 100644 --- a/twilio/rest/flex_api/v1/plugin/__init__.py +++ b/twilio/rest/flex_api/v1/plugin/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginContext] = None @property @@ -105,6 +107,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def update( self, flex_metadata: Union[str, object] = values.unset, @@ -147,6 +177,48 @@ async def update_async( description=description, ) + def update_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + async def update_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + @property def plugin_versions(self) -> PluginVersionsList: """ @@ -183,6 +255,28 @@ def __init__(self, version: Version, sid: str): self._plugin_versions: Optional[PluginVersionsList] = None + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInstance: """ Fetch the PluginInstance @@ -191,26 +285,54 @@ def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInsta :returns: The fetched PluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param flex_metadata: The Flex-Metadata HTTP request header - return PluginInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -222,41 +344,44 @@ async def fetch_async( :returns: The fetched PluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginInstance and return response metadata - headers["Accept"] = "application/json" + :param flex_metadata: The Flex-Metadata HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata ) - - return PluginInstance( + instance = PluginInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update( + def _update( self, flex_metadata: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> PluginInstance: + ) -> tuple: """ - Update the PluginInstance + Internal helper for update operation - :param flex_metadata: The Flex-Metadata HTTP request header - :param friendly_name: The Flex Plugin's friendly name. - :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long - - :returns: The updated PluginInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -277,20 +402,18 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, flex_metadata: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, ) -> PluginInstance: """ - Asynchronous coroutine to update the PluginInstance + Update the PluginInstance :param flex_metadata: The Flex-Metadata HTTP request header :param friendly_name: The Flex Plugin's friendly name. @@ -298,6 +421,48 @@ async def update_async( :returns: The updated PluginInstance """ + payload, _, _ = self._update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -317,12 +482,55 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronous coroutine to update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + payload, _, _ = await self._update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) return PluginInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def plugin_versions(self) -> PluginVersionsList: """ @@ -353,6 +561,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginInstance: :param payload: Payload response from the API """ + return PluginInstance(self._version, payload) def __repr__(self) -> str: @@ -377,22 +586,18 @@ def __init__(self, version: Version): self._uri = "/PluginService/Plugins" - def create( + def _create( self, unique_name: str, flex_metadata: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> PluginInstance: + ) -> tuple: """ - Create the PluginInstance + Internal helper for create operation - :param unique_name: The Flex Plugin's unique name. - :param flex_metadata: The Flex-Metadata HTTP request header - :param friendly_name: The Flex Plugin's friendly name. - :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long - - :returns: The created PluginInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -413,13 +618,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, flex_metadata: Union[str, object] = values.unset, @@ -427,7 +630,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> PluginInstance: """ - Asynchronously create the PluginInstance + Create the PluginInstance :param unique_name: The Flex Plugin's unique name. :param flex_metadata: The Flex-Metadata HTTP request header @@ -436,6 +639,53 @@ async def create_async( :returns: The created PluginInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginInstance and return response metadata + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -455,12 +705,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronously create the PluginInstance + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: The created PluginInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) return PluginInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PluginInstance and return response metadata + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, flex_metadata: Union[str, object] = values.unset, @@ -517,6 +816,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -538,6 +893,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -567,6 +923,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -576,6 +933,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -658,6 +1071,92 @@ async def page_async( ) return PluginPage(self._version, response) + def page_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PluginPage: """ Retrieve a specific page of PluginInstance records from the API. diff --git a/twilio/rest/flex_api/v1/plugin/plugin_versions.py b/twilio/rest/flex_api/v1/plugin/plugin_versions.py index 4d66ef572b..acd3330caa 100644 --- a/twilio/rest/flex_api/v1/plugin/plugin_versions.py +++ b/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "plugin_sid": plugin_sid, "sid": sid or self.sid, } + self._context: Optional[PluginVersionsContext] = None @property @@ -110,6 +112,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +171,28 @@ def __init__(self, version: Version, plugin_sid: str, sid: str): **self._solution ) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginVersionsInstance: @@ -151,27 +203,56 @@ def fetch( :returns: The fetched PluginVersionsInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param flex_metadata: The Flex-Metadata HTTP request header - return PluginVersionsInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -183,27 +264,34 @@ async def fetch_async( :returns: The fetched PluginVersionsInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance and return response metadata - headers["Accept"] = "application/json" + :param flex_metadata: The Flex-Metadata HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata ) - - return PluginVersionsInstance( + instance = PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -223,6 +311,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginVersionsInstance: :param payload: Payload response from the API """ + return PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"] ) @@ -256,33 +345,26 @@ def __init__(self, version: Version, plugin_sid: str): **self._solution ) - def create( + def _create( self, - version: str, + resource_version: str, plugin_url: str, flex_metadata: Union[str, object] = values.unset, changelog: Union[str, object] = values.unset, private: Union[bool, object] = values.unset, cli_version: Union[str, object] = values.unset, validate_status: Union[str, object] = values.unset, - ) -> PluginVersionsInstance: + ) -> tuple: """ - Create the PluginVersionsInstance + Internal helper for create operation - :param version: The Flex Plugin Version's version. - :param plugin_url: The URL of the Flex Plugin Version bundle - :param flex_metadata: The Flex-Metadata HTTP request header - :param changelog: The changelog of the Flex Plugin Version. - :param private: Whether this Flex Plugin Version requires authorization. - :param cli_version: The version of Flex Plugins CLI used to create this plugin - :param validate_status: The validation status of the plugin, indicating whether it has been validated - - :returns: The created PluginVersionsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "Version": version, + "Version": resource_version, "PluginUrl": plugin_url, "Changelog": changelog, "Private": serialize.boolean_to_string(private), @@ -301,28 +383,60 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Create the PluginVersionsInstance + + :param resource_version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + payload, _, _ = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) return PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"] ) - async def create_async( + def create_with_http_info( self, - version: str, + resource_version: str, plugin_url: str, flex_metadata: Union[str, object] = values.unset, changelog: Union[str, object] = values.unset, private: Union[bool, object] = values.unset, cli_version: Union[str, object] = values.unset, validate_status: Union[str, object] = values.unset, - ) -> PluginVersionsInstance: + ) -> ApiResponse: """ - Asynchronously create the PluginVersionsInstance + Create the PluginVersionsInstance and return response metadata - :param version: The Flex Plugin Version's version. + :param resource_version: The Flex Plugin Version's version. :param plugin_url: The URL of the Flex Plugin Version bundle :param flex_metadata: The Flex-Metadata HTTP request header :param changelog: The changelog of the Flex Plugin Version. @@ -330,12 +444,42 @@ async def create_async( :param cli_version: The version of Flex Plugins CLI used to create this plugin :param validate_status: The validation status of the plugin, indicating whether it has been validated - :returns: The created PluginVersionsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + instance = PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "Version": version, + "Version": resource_version, "PluginUrl": plugin_url, "Changelog": changelog, "Private": serialize.boolean_to_string(private), @@ -354,14 +498,83 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Asynchronously create the PluginVersionsInstance + + :param resource_version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + payload, _, _ = await self._create_async( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) return PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"] ) + async def create_with_http_info_async( + self, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PluginVersionsInstance and return response metadata + + :param resource_version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + instance = PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, flex_metadata: Union[str, object] = values.unset, @@ -418,6 +631,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -439,6 +708,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -468,6 +738,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -477,6 +748,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -516,7 +843,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) async def page_async( self, @@ -557,7 +884,93 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginVersionsPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginVersionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginVersionsPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginVersionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PluginVersionsPage: """ @@ -569,7 +982,7 @@ def get_page(self, target_url: str) -> PluginVersionsPage: :returns: Page of PluginVersionsInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PluginVersionsPage: """ @@ -581,7 +994,7 @@ async def get_page_async(self, target_url: str) -> PluginVersionsPage: :returns: Page of PluginVersionsInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PluginVersionsContext: """ diff --git a/twilio/rest/flex_api/v1/plugin_archive.py b/twilio/rest/flex_api/v1/plugin_archive.py index e7f526a919..7dbb89ffdc 100644 --- a/twilio/rest/flex_api/v1/plugin_archive.py +++ b/twilio/rest/flex_api/v1/plugin_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginArchiveContext] = None @property @@ -101,6 +103,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -128,15 +158,12 @@ def __init__(self, version: Version, sid: str): } self._uri = "/PluginService/Plugins/{sid}/Archive".format(**self._solution) - def update( - self, flex_metadata: Union[str, object] = values.unset - ) -> PluginArchiveInstance: + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: """ - Update the PluginArchiveInstance - - :param flex_metadata: The Flex-Metadata HTTP request header + Internal helper for update operation - :returns: The updated PluginArchiveInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -150,22 +177,48 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, flex_metadata: Union[str, object] = values.unset ) -> PluginArchiveInstance: """ - Asynchronous coroutine to update the PluginArchiveInstance + Update the PluginArchiveInstance :param flex_metadata: The Flex-Metadata HTTP request header :returns: The updated PluginArchiveInstance """ + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of({}) headers = values.of({}) @@ -178,12 +231,41 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginArchiveInstance: + """ + Asynchronous coroutine to update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py index b17d697e3b..d98e1f3615 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py +++ b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginConfigurationContext] = None @property @@ -101,6 +103,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + @property def plugins(self) -> ConfiguredPluginList: """ @@ -137,6 +167,28 @@ def __init__(self, version: Version, sid: str): self._plugins: Optional[ConfiguredPluginList] = None + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginConfigurationInstance: @@ -147,26 +199,54 @@ def fetch( :returns: The fetched PluginConfigurationInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param flex_metadata: The Flex-Metadata HTTP request header - return PluginConfigurationInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginConfigurationInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -178,26 +258,32 @@ async def fetch_async( :returns: The fetched PluginConfigurationInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance and return response metadata - headers["Accept"] = "application/json" + :param flex_metadata: The Flex-Metadata HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata ) - - return PluginConfigurationInstance( + instance = PluginConfigurationInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def plugins(self) -> ConfiguredPluginList: @@ -229,6 +315,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginConfigurationInstance: :param payload: Payload response from the API """ + return PluginConfigurationInstance(self._version, payload) def __repr__(self) -> str: @@ -253,22 +340,18 @@ def __init__(self, version: Version): self._uri = "/PluginService/Configurations" - def create( + def _create( self, name: str, flex_metadata: Union[str, object] = values.unset, plugins: Union[List[object], object] = values.unset, description: Union[str, object] = values.unset, - ) -> PluginConfigurationInstance: + ) -> tuple: """ - Create the PluginConfigurationInstance - - :param name: The Flex Plugin Configuration's name. - :param flex_metadata: The Flex-Metadata HTTP request header - :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. - :param description: The Flex Plugin Configuration's description. + Internal helper for create operation - :returns: The created PluginConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -289,13 +372,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, name: str, flex_metadata: Union[str, object] = values.unset, @@ -303,7 +384,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> PluginConfigurationInstance: """ - Asynchronously create the PluginConfigurationInstance + Create the PluginConfigurationInstance :param name: The Flex Plugin Configuration's name. :param flex_metadata: The Flex-Metadata HTTP request header @@ -312,6 +393,53 @@ async def create_async( :returns: The created PluginConfigurationInstance """ + payload, _, _ = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + return PluginConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginConfigurationInstance and return response metadata + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + instance = PluginConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -331,12 +459,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + Asynchronously create the PluginConfigurationInstance + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: The created PluginConfigurationInstance + """ + payload, _, _ = await self._create_async( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) return PluginConfigurationInstance(self._version, payload) + async def create_with_http_info_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PluginConfigurationInstance and return response metadata + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + instance = PluginConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, flex_metadata: Union[str, object] = values.unset, @@ -393,6 +570,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -414,6 +647,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -443,6 +677,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -452,6 +687,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -534,6 +825,92 @@ async def page_async( ) return PluginConfigurationPage(self._version, response) + def page_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginConfigurationPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginConfigurationPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PluginConfigurationPage: """ Retrieve a specific page of PluginConfigurationInstance records from the API. diff --git a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py index 062a7db7b4..473f86f966 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py +++ b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "configuration_sid": configuration_sid, "plugin_sid": plugin_sid or self.plugin_sid, } + self._context: Optional[ConfiguredPluginContext] = None @property @@ -122,6 +124,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -153,6 +183,28 @@ def __init__(self, version: Version, configuration_sid: str, plugin_sid: str): **self._solution ) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> ConfiguredPluginInstance: @@ -163,27 +215,56 @@ def fetch( :returns: The fetched ConfiguredPluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param flex_metadata: The Flex-Metadata HTTP request header - return ConfiguredPluginInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = ConfiguredPluginInstance( self._version, payload, configuration_sid=self._solution["configuration_sid"], plugin_sid=self._solution["plugin_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -195,27 +276,34 @@ async def fetch_async( :returns: The fetched ConfiguredPluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance and return response metadata - headers["Accept"] = "application/json" + :param flex_metadata: The Flex-Metadata HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata ) - - return ConfiguredPluginInstance( + instance = ConfiguredPluginInstance( self._version, payload, configuration_sid=self._solution["configuration_sid"], plugin_sid=self._solution["plugin_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -235,6 +323,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConfiguredPluginInstance: :param payload: Payload response from the API """ + return ConfiguredPluginInstance( self._version, payload, @@ -326,6 +415,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -347,6 +492,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -376,6 +522,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -385,6 +532,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -424,7 +627,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) async def page_async( self, @@ -465,7 +668,93 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfiguredPluginPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfiguredPluginPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfiguredPluginPage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfiguredPluginPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConfiguredPluginPage: """ @@ -477,7 +766,7 @@ def get_page(self, target_url: str) -> ConfiguredPluginPage: :returns: Page of ConfiguredPluginInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: """ @@ -489,7 +778,7 @@ async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: :returns: Page of ConfiguredPluginInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) def get(self, plugin_sid: str) -> ConfiguredPluginContext: """ diff --git a/twilio/rest/flex_api/v1/plugin_configuration_archive.py b/twilio/rest/flex_api/v1/plugin_configuration_archive.py index 3fec073333..e880c68ec4 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration_archive.py +++ b/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginConfigurationArchiveContext] = None @property @@ -95,6 +97,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,15 +156,12 @@ def __init__(self, version: Version, sid: str): **self._solution ) - def update( - self, flex_metadata: Union[str, object] = values.unset - ) -> PluginConfigurationArchiveInstance: + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: """ - Update the PluginConfigurationArchiveInstance - - :param flex_metadata: The Flex-Metadata HTTP request header + Internal helper for update operation - :returns: The updated PluginConfigurationArchiveInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -148,23 +175,49 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + payload, _, _ = self._update(flex_metadata=flex_metadata) return PluginConfigurationArchiveInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, flex_metadata: Union[str, object] = values.unset - ) -> PluginConfigurationArchiveInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PluginConfigurationArchiveInstance + Update the PluginConfigurationArchiveInstance and return response metadata :param flex_metadata: The Flex-Metadata HTTP request header - :returns: The updated PluginConfigurationArchiveInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -178,14 +231,43 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) return PluginConfigurationArchiveInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/plugin_release.py b/twilio/rest/flex_api/v1/plugin_release.py index 0694b05f8b..08d3bbd00f 100644 --- a/twilio/rest/flex_api/v1/plugin_release.py +++ b/twilio/rest/flex_api/v1/plugin_release.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginReleaseContext] = None @property @@ -92,6 +94,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,6 +149,28 @@ def __init__(self, version: Version, sid: str): } self._uri = "/PluginService/Releases/{sid}".format(**self._solution) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginReleaseInstance: @@ -129,26 +181,54 @@ def fetch( :returns: The fetched PluginReleaseInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) - - headers["Accept"] = "application/json" + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance and return response metadata - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers - ) + :param flex_metadata: The Flex-Metadata HTTP request header - return PluginReleaseInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginReleaseInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -160,26 +240,32 @@ async def fetch_async( :returns: The fetched PluginReleaseInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], ) - headers = values.of({}) + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance and return response metadata - headers["Accept"] = "application/json" + :param flex_metadata: The Flex-Metadata HTTP request header - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata ) - - return PluginReleaseInstance( + instance = PluginReleaseInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -199,6 +285,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginReleaseInstance: :param payload: Payload response from the API """ + return PluginReleaseInstance(self._version, payload) def __repr__(self) -> str: @@ -223,16 +310,14 @@ def __init__(self, version: Version): self._uri = "/PluginService/Releases" - def create( + def _create( self, configuration_id: str, flex_metadata: Union[str, object] = values.unset - ) -> PluginReleaseInstance: + ) -> tuple: """ - Create the PluginReleaseInstance + Internal helper for create operation - :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. - :param flex_metadata: The Flex-Metadata HTTP request header - - :returns: The created PluginReleaseInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -251,23 +336,52 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginReleaseInstance(self._version, payload) - - async def create_async( + def create( self, configuration_id: str, flex_metadata: Union[str, object] = values.unset ) -> PluginReleaseInstance: """ - Asynchronously create the PluginReleaseInstance + Create the PluginReleaseInstance :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. :param flex_metadata: The Flex-Metadata HTTP request header :returns: The created PluginReleaseInstance """ + payload, _, _ = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + return PluginReleaseInstance(self._version, payload) + + def create_with_http_info( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the PluginReleaseInstance and return response metadata + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -285,12 +399,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Asynchronously create the PluginReleaseInstance + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The created PluginReleaseInstance + """ + payload, _, _ = await self._create_async( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) return PluginReleaseInstance(self._version, payload) + async def create_with_http_info_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the PluginReleaseInstance and return response metadata + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, flex_metadata: Union[str, object] = values.unset, @@ -347,6 +492,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -368,6 +569,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -397,6 +599,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -406,6 +609,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -488,6 +747,92 @@ async def page_async( ) return PluginReleasePage(self._version, response) + def page_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginReleasePage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PluginReleasePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PluginReleasePage, status code, and headers + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PluginReleasePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PluginReleasePage: """ Retrieve a specific page of PluginReleaseInstance records from the API. diff --git a/twilio/rest/flex_api/v1/plugin_version_archive.py b/twilio/rest/flex_api/v1/plugin_version_archive.py index be169d4d64..d2b601a828 100644 --- a/twilio/rest/flex_api/v1/plugin_version_archive.py +++ b/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "plugin_sid": plugin_sid or self.plugin_sid, "sid": sid or self.sid, } + self._context: Optional[PluginVersionArchiveContext] = None @property @@ -107,6 +109,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,15 +168,12 @@ def __init__(self, version: Version, plugin_sid: str, sid: str): **self._solution ) - def update( - self, flex_metadata: Union[str, object] = values.unset - ) -> PluginVersionArchiveInstance: + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: """ - Update the PluginVersionArchiveInstance + Internal helper for update operation - :param flex_metadata: The Flex-Metadata HTTP request header - - :returns: The updated PluginVersionArchiveInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -160,10 +187,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + payload, _, _ = self._update(flex_metadata=flex_metadata) return PluginVersionArchiveInstance( self._version, payload, @@ -171,15 +209,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, flex_metadata: Union[str, object] = values.unset - ) -> PluginVersionArchiveInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PluginVersionArchiveInstance + Update the PluginVersionArchiveInstance and return response metadata :param flex_metadata: The Flex-Metadata HTTP request header - :returns: The updated PluginVersionArchiveInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(flex_metadata=flex_metadata) + instance = PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -193,10 +249,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) return PluginVersionArchiveInstance( self._version, payload, @@ -204,6 +271,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance and return response metadata + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + flex_metadata=flex_metadata + ) + instance = PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/provisioning_status.py b/twilio/rest/flex_api/v1/provisioning_status.py index 2a7bc5b465..a13a1baab7 100644 --- a/twilio/rest/flex_api/v1/provisioning_status.py +++ b/twilio/rest/flex_api/v1/provisioning_status.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,24 @@ async def fetch_async(self) -> "ProvisioningStatusInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -97,46 +116,92 @@ def __init__(self, version: Version): self._uri = "/account/provision/status" - def fetch(self) -> ProvisioningStatusInstance: + def _fetch(self) -> tuple: """ - Fetch the ProvisioningStatusInstance + Internal helper for fetch operation - - :returns: The fetched ProvisioningStatusInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ProvisioningStatusInstance: + """ + Fetch the ProvisioningStatusInstance + + :returns: The fetched ProvisioningStatusInstance + """ + payload, _, _ = self._fetch() return ProvisioningStatusInstance( self._version, payload, ) - async def fetch_async(self) -> ProvisioningStatusInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ProvisioningStatusInstance + Fetch the ProvisioningStatusInstance and return response metadata - :returns: The fetched ProvisioningStatusInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ProvisioningStatusInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ProvisioningStatusInstance: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + payload, _, _ = await self._fetch_async() return ProvisioningStatusInstance( self._version, payload, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ProvisioningStatusInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/web_channel.py b/twilio/rest/flex_api/v1/web_channel.py index 46e44fcecd..0b0560cb89 100644 --- a/twilio/rest/flex_api/v1/web_channel.py +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[WebChannelContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebChannelInstance": """ Fetch the WebChannelInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "WebChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, @@ -144,6 +182,42 @@ async def update_async( post_engagement_data=post_engagement_data, ) + def update_with_http_info( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebChannelInstance with HTTP info + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + async def update_with_http_info_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebChannelInstance with HTTP info + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +245,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/WebChannels/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebChannelInstance @@ -178,10 +266,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -190,67 +300,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebChannelInstance: + """ + Fetch the WebChannelInstance + + :returns: The fetched WebChannelInstance + """ + payload, _, _ = self._fetch() return WebChannelInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> WebChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebChannelInstance + Fetch the WebChannelInstance and return response metadata - :returns: The fetched WebChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebChannelInstance: + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + payload, _, _ = await self._fetch_async() return WebChannelInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, post_engagement_data: Union[str, object] = values.unset, - ) -> WebChannelInstance: + ) -> tuple: """ - Update the WebChannelInstance + Internal helper for update operation - :param chat_status: - :param post_engagement_data: The post-engagement data. - - :returns: The updated WebChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -265,25 +427,58 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, post_engagement_data: Union[str, object] = values.unset, ) -> WebChannelInstance: """ - Asynchronous coroutine to update the WebChannelInstance + Update the WebChannelInstance :param chat_status: :param post_engagement_data: The post-engagement data. :returns: The updated WebChannelInstance """ + payload, _, _ = self._update( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebChannelInstance and return response metadata + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + instance = WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -297,12 +492,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + payload, _, _ = await self._update_async( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebChannelInstance and return response metadata + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + chat_status=chat_status, post_engagement_data=post_engagement_data + ) + instance = WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -321,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: :param payload: Payload response from the API """ + return WebChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -345,7 +576,7 @@ def __init__(self, version: Version): self._uri = "/WebChannels" - def create( + def _create( self, flex_flow_sid: str, identity: str, @@ -353,18 +584,12 @@ def create( chat_friendly_name: str, chat_unique_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, - ) -> WebChannelInstance: + ) -> tuple: """ - Create the WebChannelInstance - - :param flex_flow_sid: The SID of the Flex Flow. - :param identity: The chat identity. - :param customer_friendly_name: The chat participant's friendly name. - :param chat_friendly_name: The chat channel's friendly name. - :param chat_unique_name: The chat channel's unique name. - :param pre_engagement_data: The pre-engagement data. + Internal helper for create operation - :returns: The created WebChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -383,13 +608,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WebChannelInstance(self._version, payload) - - async def create_async( + def create( self, flex_flow_sid: str, identity: str, @@ -399,7 +622,7 @@ async def create_async( pre_engagement_data: Union[str, object] = values.unset, ) -> WebChannelInstance: """ - Asynchronously create the WebChannelInstance + Create the WebChannelInstance :param flex_flow_sid: The SID of the Flex Flow. :param identity: The chat identity. @@ -410,6 +633,63 @@ async def create_async( :returns: The created WebChannelInstance """ + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + return WebChannelInstance(self._version, payload) + + def create_with_http_info( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WebChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -427,12 +707,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronously create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) return WebChannelInstance(self._version, payload) + async def create_with_http_info_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -483,6 +824,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -502,6 +893,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -528,6 +920,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -536,6 +929,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -602,6 +1045,76 @@ async def page_async( ) return WebChannelPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebChannelPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> WebChannelPage: """ Retrieve a specific page of WebChannelInstance records from the API. diff --git a/twilio/rest/flex_api/v2/flex_user.py b/twilio/rest/flex_api/v2/flex_user.py index 480a439b85..70ed7b7ac6 100644 --- a/twilio/rest/flex_api/v2/flex_user.py +++ b/twilio/rest/flex_api/v2/flex_user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,11 +31,8 @@ class FlexUserInstance(InstanceResource): :ivar worker_sid: The unique SID identifier of the worker. :ivar workspace_sid: The unique SID identifier of the workspace. :ivar flex_team_sid: The unique SID identifier of the Flex Team. - :ivar first_name: First name of the User. - :ivar last_name: Last name of the User. :ivar username: Username of the User. :ivar email: Email of the User. - :ivar friendly_name: Friendly name of the User. :ivar locale: The locale preference of the user. :ivar roles: The roles of the user. :ivar created_date: The date that this user was created, given in ISO 8601 format. @@ -59,11 +57,8 @@ def __init__( self.worker_sid: Optional[str] = payload.get("worker_sid") self.workspace_sid: Optional[str] = payload.get("workspace_sid") self.flex_team_sid: Optional[str] = payload.get("flex_team_sid") - self.first_name: Optional[str] = payload.get("first_name") - self.last_name: Optional[str] = payload.get("last_name") self.username: Optional[str] = payload.get("username") self.email: Optional[str] = payload.get("email") - self.friendly_name: Optional[str] = payload.get("friendly_name") self.locale: Optional[str] = payload.get("locale") self.roles: Optional[List[str]] = payload.get("roles") self.created_date: Optional[datetime] = deserialize.iso8601_datetime( @@ -79,6 +74,7 @@ def __init__( "instance_sid": instance_sid or self.instance_sid, "flex_user_sid": flex_user_sid or self.flex_user_sid, } + self._context: Optional[FlexUserContext] = None @property @@ -115,62 +111,104 @@ async def fetch_async(self) -> "FlexUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, - first_name: Union[str, object] = values.unset, - last_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, user_sid: Union[str, object] = values.unset, locale: Union[str, object] = values.unset, ) -> "FlexUserInstance": """ Update the FlexUserInstance - :param first_name: First name of the User. - :param last_name: Last name of the User. :param email: Email of the User. - :param friendly_name: Friendly name of the User. :param user_sid: The unique SID identifier of the Twilio Unified User. :param locale: The locale preference of the user. :returns: The updated FlexUserInstance """ return self._proxy.update( - first_name=first_name, - last_name=last_name, email=email, - friendly_name=friendly_name, user_sid=user_sid, locale=locale, ) async def update_async( self, - first_name: Union[str, object] = values.unset, - last_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, user_sid: Union[str, object] = values.unset, locale: Union[str, object] = values.unset, ) -> "FlexUserInstance": """ Asynchronous coroutine to update the FlexUserInstance - :param first_name: First name of the User. - :param last_name: Last name of the User. :param email: Email of the User. - :param friendly_name: Friendly name of the User. :param user_sid: The unique SID identifier of the Twilio Unified User. :param locale: The locale preference of the user. :returns: The updated FlexUserInstance """ return await self._proxy.update_async( - first_name=first_name, - last_name=last_name, email=email, - friendly_name=friendly_name, + user_sid=user_sid, + locale=locale, + ) + + def update_with_http_info( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexUserInstance with HTTP info + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + email=email, + user_sid=user_sid, + locale=locale, + ) + + async def update_with_http_info_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexUserInstance with HTTP info + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + email=email, user_sid=user_sid, locale=locale, ) @@ -206,20 +244,30 @@ def __init__(self, version: Version, instance_sid: str, flex_user_sid: str): **self._solution ) - def fetch(self) -> FlexUserInstance: + def _fetch(self) -> tuple: """ - Fetch the FlexUserInstance + Internal helper for fetch operation - - :returns: The fetched FlexUserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlexUserInstance: + """ + Fetch the FlexUserInstance + + :returns: The fetched FlexUserInstance + """ + payload, _, _ = self._fetch() return FlexUserInstance( self._version, payload, @@ -227,22 +275,46 @@ def fetch(self) -> FlexUserInstance: flex_user_sid=self._solution["flex_user_sid"], ) - async def fetch_async(self) -> FlexUserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlexUserInstance + Fetch the FlexUserInstance and return response metadata - :returns: The fetched FlexUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlexUserInstance: + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + payload, _, _ = await self._fetch_async() return FlexUserInstance( self._version, payload, @@ -250,34 +322,38 @@ async def fetch_async(self) -> FlexUserInstance: flex_user_sid=self._solution["flex_user_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, - first_name: Union[str, object] = values.unset, - last_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, user_sid: Union[str, object] = values.unset, locale: Union[str, object] = values.unset, - ) -> FlexUserInstance: + ) -> tuple: """ - Update the FlexUserInstance - - :param first_name: First name of the User. - :param last_name: Last name of the User. - :param email: Email of the User. - :param friendly_name: Friendly name of the User. - :param user_sid: The unique SID identifier of the Twilio Unified User. - :param locale: The locale preference of the user. + Internal helper for update operation - :returns: The updated FlexUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "FirstName": first_name, - "LastName": last_name, "Email": email, - "FriendlyName": friendly_name, "UserSid": user_sid, "Locale": locale, } @@ -288,10 +364,26 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + payload, _, _ = self._update(email=email, user_sid=user_sid, locale=locale) return FlexUserInstance( self._version, payload, @@ -299,34 +391,48 @@ def update( flex_user_sid=self._solution["flex_user_sid"], ) - async def update_async( + def update_with_http_info( self, - first_name: Union[str, object] = values.unset, - last_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, user_sid: Union[str, object] = values.unset, locale: Union[str, object] = values.unset, - ) -> FlexUserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the FlexUserInstance + Update the FlexUserInstance and return response metadata - :param first_name: First name of the User. - :param last_name: Last name of the User. :param email: Email of the User. - :param friendly_name: Friendly name of the User. :param user_sid: The unique SID identifier of the Twilio Unified User. :param locale: The locale preference of the user. - :returns: The updated FlexUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + email=email, user_sid=user_sid, locale=locale + ) + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "FirstName": first_name, - "LastName": last_name, "Email": email, - "FriendlyName": friendly_name, "UserSid": user_sid, "Locale": locale, } @@ -337,10 +443,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Asynchronous coroutine to update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + payload, _, _ = await self._update_async( + email=email, user_sid=user_sid, locale=locale + ) return FlexUserInstance( self._version, payload, @@ -348,6 +472,32 @@ async def update_async( flex_user_sid=self._solution["flex_user_sid"], ) + async def update_with_http_info_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexUserInstance and return response metadata + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + email=email, user_sid=user_sid, locale=locale + ) + instance = FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v2/web_channels.py b/twilio/rest/flex_api/v2/web_channels.py index 8e5aff8226..f25f907348 100644 --- a/twilio/rest/flex_api/v2/web_channels.py +++ b/twilio/rest/flex_api/v2/web_channels.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,24 +56,20 @@ def __init__(self, version: Version): self._uri = "/WebChats" - def create( + def _create( self, address_sid: str, ui_version: Union[str, object] = values.unset, chat_friendly_name: Union[str, object] = values.unset, customer_friendly_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, - ) -> WebChannelsInstance: + identity: Union[str, object] = values.unset, + ) -> tuple: """ - Create the WebChannelsInstance + Internal helper for create operation - :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. - :param ui_version: The Ui-Version HTTP request header - :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. - :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. - :param pre_engagement_data: The pre-engagement data. - - :returns: The created WebChannelsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -81,6 +78,7 @@ def create( "ChatFriendlyName": chat_friendly_name, "CustomerFriendlyName": customer_friendly_name, "PreEngagementData": pre_engagement_data, + "Identity": identity, } ) headers = values.of( @@ -94,31 +92,88 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WebChannelsInstance(self._version, payload) - - async def create_async( + def create( self, address_sid: str, ui_version: Union[str, object] = values.unset, chat_friendly_name: Union[str, object] = values.unset, customer_friendly_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, ) -> WebChannelsInstance: """ - Asynchronously create the WebChannelsInstance + Create the WebChannelsInstance :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. :param ui_version: The Ui-Version HTTP request header :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. :returns: The created WebChannelsInstance """ + payload, _, _ = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + return WebChannelsInstance(self._version, payload) + + def create_with_http_info( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WebChannelsInstance and return response metadata + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -126,6 +181,7 @@ async def create_async( "ChatFriendlyName": chat_friendly_name, "CustomerFriendlyName": customer_friendly_name, "PreEngagementData": pre_engagement_data, + "Identity": identity, } ) headers = values.of( @@ -139,12 +195,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Asynchronously create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: The created WebChannelsInstance + """ + payload, _, _ = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) return WebChannelsInstance(self._version, payload) + async def create_with_http_info_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebChannelsInstance and return response metadata + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/frontline_api/v1/user.py b/twilio/rest/frontline_api/v1/user.py index a45ed2ffee..f3cb7f3b25 100644 --- a/twilio/rest/frontline_api/v1/user.py +++ b/twilio/rest/frontline_api/v1/user.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -135,6 +155,54 @@ async def update_async( is_available=is_available, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,64 +230,108 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Users/{sid}".format(**self._solution) - def fetch(self) -> UserInstance: + def _fetch(self) -> tuple: """ - Fetch the UserInstance + Internal helper for fetch operation - - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, avatar: Union[str, object] = values.unset, state: Union["UserInstance.StateType", object] = values.unset, is_available: Union[bool, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance - - :param friendly_name: The string that you assigned to describe the User. - :param avatar: The avatar URL which will be shown in Frontline application. - :param state: - :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + Internal helper for update operation - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -236,13 +348,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return UserInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, avatar: Union[str, object] = values.unset, @@ -250,7 +360,7 @@ async def update_async( is_available: Union[bool, object] = values.unset, ) -> UserInstance: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance :param friendly_name: The string that you assigned to describe the User. :param avatar: The avatar URL which will be shown in Frontline application. @@ -259,6 +369,53 @@ async def update_async( :returns: The updated UserInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -274,12 +431,61 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) return UserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + instance = UserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/iam/v1/__init__.py b/twilio/rest/iam/v1/__init__.py index 408de11acb..cef8af5122 100644 --- a/twilio/rest/iam/v1/__init__.py +++ b/twilio/rest/iam/v1/__init__.py @@ -17,7 +17,10 @@ from twilio.base.domain import Domain from twilio.rest.iam.v1.api_key import ApiKeyList from twilio.rest.iam.v1.get_api_keys import GetApiKeysList -from twilio.rest.iam.v1.key import KeyList +from twilio.rest.iam.v1.new_api_key import NewApiKeyList +from twilio.rest.iam.v1.o_auth_app import OAuthAppList +from twilio.rest.iam.v1.role_permission import RolePermissionList +from twilio.rest.iam.v1.token import TokenList class V1(Version): @@ -31,7 +34,9 @@ def __init__(self, domain: Domain): super().__init__(domain, "v1") self._api_key: Optional[ApiKeyList] = None self._get_api_keys: Optional[GetApiKeysList] = None - self._keys: Optional[KeyList] = None + self._new_api_key: Optional[NewApiKeyList] = None + self._o_auth_apps: Optional[OAuthAppList] = None + self._token: Optional[TokenList] = None @property def api_key(self) -> ApiKeyList: @@ -46,10 +51,36 @@ def get_api_keys(self) -> GetApiKeysList: return self._get_api_keys @property - def keys(self) -> KeyList: - if self._keys is None: - self._keys = KeyList(self) - return self._keys + def new_api_key(self) -> NewApiKeyList: + if self._new_api_key is None: + self._new_api_key = NewApiKeyList(self) + return self._new_api_key + + @property + def o_auth_apps(self) -> OAuthAppList: + if self._o_auth_apps is None: + self._o_auth_apps = OAuthAppList(self) + return self._o_auth_apps + + def role_permission(self, role_sid: str, role_permission_id: str = None): + """ + Access the RolePermissionList resource + + :param role_sid: The SID of the Role for which Permissions will be fetched. + + :param role_permission_id: Optional instance ID to directly access RolePermissionContext + :returns: RolePermissionList instance if role_permission_id is None, otherwise RolePermissionContext + """ + list_instance = RolePermissionList(self, role_sid) + if role_permission_id is not None: + return list_instance(role_permission_id) + return list_instance + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token def __repr__(self) -> str: """ diff --git a/twilio/rest/iam/v1/api_key.py b/twilio/rest/iam/v1/api_key.py index f07512c09b..c99f3ff2a5 100644 --- a/twilio/rest/iam/v1/api_key.py +++ b/twilio/rest/iam/v1/api_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ApiKeyContext] = None @property @@ -83,6 +85,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ApiKeyInstance": """ Fetch the ApiKeyInstance @@ -101,6 +121,24 @@ async def fetch_async(self) -> "ApiKeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApiKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -137,6 +175,42 @@ async def update_async( policy=policy, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApiKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + policy=policy, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApiKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + policy=policy, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,6 +238,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Keys/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ApiKeyInstance @@ -171,10 +259,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -183,67 +293,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApiKeyInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ApiKeyInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ApiKeyInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ApiKeyInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApiKeyInstance: + """ + Fetch the ApiKeyInstance + + :returns: The fetched ApiKeyInstance + """ + payload, _, _ = self._fetch() return ApiKeyInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ApiKeyInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ApiKeyInstance + Fetch the ApiKeyInstance and return response metadata - :returns: The fetched ApiKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ApiKeyInstance: + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + payload, _, _ = await self._fetch_async() return ApiKeyInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApiKeyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, policy: Union[object, object] = values.unset, - ) -> ApiKeyInstance: + ) -> tuple: """ - Update the ApiKeyInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). - - :returns: The updated ApiKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -258,25 +420,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, policy: Union[object, object] = values.unset, ) -> ApiKeyInstance: """ - Asynchronous coroutine to update the ApiKeyInstance + Update the ApiKeyInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). :returns: The updated ApiKeyInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, policy=policy) + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApiKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, policy=policy + ) + instance = ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -290,12 +483,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiKeyInstance: + """ + Asynchronous coroutine to update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, policy=policy + ) return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApiKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, policy=policy + ) + instance = ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/iam/v1/get_api_keys.py b/twilio/rest/iam/v1/get_api_keys.py index 03b29cdb38..14bd127d89 100644 --- a/twilio/rest/iam/v1/get_api_keys.py +++ b/twilio/rest/iam/v1/get_api_keys.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class GetApiKeysInstance(InstanceResource): :ivar friendly_name: The string that you assigned to describe the resource. :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar flags: """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -41,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( payload.get("date_updated") ) + self.flags: Optional[List[str]] = payload.get("flags") def __repr__(self) -> str: """ @@ -60,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> GetApiKeysInstance: :param payload: Payload response from the API """ + return GetApiKeysInstance(self._version, payload) def __repr__(self) -> str: @@ -140,6 +144,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams GetApiKeysInstance and returns headers from first page + + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + account_sid=account_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams GetApiKeysInstance and returns headers from first page + + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + account_sid=account_sid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, account_sid: Union[str, object] = values.unset, @@ -161,6 +221,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( account_sid=account_sid, @@ -190,6 +251,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -199,6 +261,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists GetApiKeysInstance and returns headers from first page + + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists GetApiKeysInstance and returns headers from first page + + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, account_sid: Union[str, object] = values.unset, @@ -271,6 +389,82 @@ async def page_async( ) return GetApiKeysPage(self._version, response) + def page_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with GetApiKeysPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = GetApiKeysPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with GetApiKeysPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = GetApiKeysPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> GetApiKeysPage: """ Retrieve a specific page of GetApiKeysInstance records from the API. diff --git a/twilio/rest/iam/v1/key.py b/twilio/rest/iam/v1/key.py deleted file mode 100644 index cd5556df94..0000000000 --- a/twilio/rest/iam/v1/key.py +++ /dev/null @@ -1,157 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Iam - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, Optional, Union -from twilio.base import deserialize, serialize, values - -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version - - -class KeyInstance(InstanceResource): - - class Keytype(object): - RESTRICTED = "restricted" - - """ - :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. - :ivar friendly_name: The string that you assigned to describe the resource. - :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. - :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. - :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** - :ivar policy: Collection of allow assertions. - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( - payload.get("date_updated") - ) - self.secret: Optional[str] = payload.get("secret") - self.policy: Optional[Dict[str, object]] = payload.get("policy") - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class KeyList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the KeyList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Keys" - - def create( - self, - account_sid: str, - friendly_name: Union[str, object] = values.unset, - key_type: Union["KeyInstance.Keytype", object] = values.unset, - policy: Union[object, object] = values.unset, - ) -> KeyInstance: - """ - Create the KeyInstance - - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param key_type: - :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). - - :returns: The created KeyInstance - """ - - data = values.of( - { - "AccountSid": account_sid, - "FriendlyName": friendly_name, - "KeyType": key_type, - "Policy": serialize.object(policy), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return KeyInstance(self._version, payload) - - async def create_async( - self, - account_sid: str, - friendly_name: Union[str, object] = values.unset, - key_type: Union["KeyInstance.Keytype", object] = values.unset, - policy: Union[object, object] = values.unset, - ) -> KeyInstance: - """ - Asynchronously create the KeyInstance - - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param key_type: - :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). - - :returns: The created KeyInstance - """ - - data = values.of( - { - "AccountSid": account_sid, - "FriendlyName": friendly_name, - "KeyType": key_type, - "Policy": serialize.object(policy), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return KeyInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/iam/v1/new_api_key.py b/twilio/rest/iam/v1/new_api_key.py new file mode 100644 index 0000000000..0a5e395ec2 --- /dev/null +++ b/twilio/rest/iam/v1/new_api_key.py @@ -0,0 +1,244 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewApiKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + :ivar policy: Collection of allow assertions. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + self.policy: Optional[Dict[str, object]] = payload.get("policy") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class NewApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NewApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def _create( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: The \\\\`KeyType\\\\` form parameter is used to specify the type of key you want to create. **Default Behavior**: If \\\\`KeyType\\\\` is not specified, the API will generate a standard key. **Restricted Key**: If \\\\`KeyType\\\\` is set to \\\\`restricted\\\\`, the API will create a new restricted key. In this case, a policy object is required to define the permissions. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + payload, _, _ = self._create( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + return NewApiKeyInstance(self._version, payload) + + def create_with_http_info( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the NewApiKeyInstance and return response metadata + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: The \\\\`KeyType\\\\` form parameter is used to specify the type of key you want to create. **Default Behavior**: If \\\\`KeyType\\\\` is not specified, the API will generate a standard key. **Restricted Key**: If \\\\`KeyType\\\\` is set to \\\\`restricted\\\\`, the API will create a new restricted key. In this case, a policy object is required to define the permissions. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + instance = NewApiKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Asynchronously create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: The \\\\`KeyType\\\\` form parameter is used to specify the type of key you want to create. **Default Behavior**: If \\\\`KeyType\\\\` is not specified, the API will generate a standard key. **Restricted Key**: If \\\\`KeyType\\\\` is set to \\\\`restricted\\\\`, the API will create a new restricted key. In this case, a policy object is required to define the permissions. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + payload, _, _ = await self._create_async( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + return NewApiKeyInstance(self._version, payload) + + async def create_with_http_info_async( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NewApiKeyInstance and return response metadata + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: The \\\\`KeyType\\\\` form parameter is used to specify the type of key you want to create. **Default Behavior**: If \\\\`KeyType\\\\` is not specified, the API will generate a standard key. **Restricted Key**: If \\\\`KeyType\\\\` is set to \\\\`restricted\\\\`, the API will create a new restricted key. In this case, a policy object is required to define the permissions. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + account_sid=account_sid, + friendly_name=friendly_name, + key_type=key_type, + policy=policy, + ) + instance = NewApiKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/o_auth_app.py b/twilio/rest/iam/v1/o_auth_app.py new file mode 100644 index 0000000000..14d069bcea --- /dev/null +++ b/twilio/rest/iam/v1/o_auth_app.py @@ -0,0 +1,852 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OAuthAppInstance(InstanceResource): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar token_endpoint_auth_method: Determines how the client authenticates. Account OAuth apps on v1 only support 'client_secret_basic'. For PKCE (none), use the v2 API. + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.token_endpoint_auth_method: Optional["OAuthAppInstance.str"] = ( + payload.get("token_endpoint_auth_method") + ) + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "token_endpoint_auth_method": self.token_endpoint_auth_method, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + """ + :ivar type: + :ivar sid: + :ivar friendly_name: + :ivar description: + :ivar date_created: + :ivar created_by: + :ivar creator_sid: The unique identifier (SID) of the user who created this OAuth app. + :ivar secret: + :ivar status: + :ivar policy: + :ivar access_token_ttl: + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.type: Optional[str] = payload.get("type") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.creator_sid: Optional[str] = payload.get("creator_sid") + self.secret: Optional[str] = payload.get("secret") + self.status: Optional[str] = payload.get("status") + self.policy: Optional[str] = payload.get("policy") + self.access_token_ttl: Optional[int] = deserialize.integer( + payload.get("access_token_ttl") + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[OAuthAppContext] = None + + @property + def _proxy(self) -> "OAuthAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OAuthAppContext for this OAuthAppInstance + """ + if self._context is None: + self._context = OAuthAppContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OAuthAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OAuthAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> "OAuthAppInstance": + """ + Update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + return self._proxy.update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + async def update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> "OAuthAppInstance": + """ + Asynchronous coroutine to update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + return await self._proxy.update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + def update_with_http_info( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Update the OAuthAppInstance with HTTP info + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + async def update_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OAuthAppInstance with HTTP info + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OAuthAppContext(InstanceContext): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar token_endpoint_auth_method: Determines how the client authenticates. Account OAuth apps on v1 only support 'client_secret_basic'. For PKCE (none), use the v2 API. + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.token_endpoint_auth_method: Optional["OAuthAppInstance.str"] = ( + payload.get("token_endpoint_auth_method") + ) + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "token_endpoint_auth_method": self.token_endpoint_auth_method, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the OAuthAppContext + + :param version: Version that contains the resource + :param sid: Unique ID (sid) of the OAuth app + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Account/OAuthApps/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OAuthAppInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OAuthAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OAuthAppInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> OAuthAppInstance: + """ + Update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + payload, _, _ = self._update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + return OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Update the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + instance = OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_update_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> OAuthAppInstance: + """ + Asynchronous coroutine to update the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: The updated OAuthAppInstance + """ + payload, _, _ = await self._update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + return OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_update_request: IamV1AccountVendorOauthAppUpdateRequest, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_update_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + iam_v1_account_vendor_oauth_app_update_request=iam_v1_account_vendor_oauth_app_update_request + ) + instance = OAuthAppInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OAuthAppList(ListResource): + + class IamV1AccountVendorOauthAppCreateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar owner_sid: + :ivar description: + :ivar client_sid: + :ivar token_endpoint_auth_method: Determines how the client authenticates. Account OAuth apps on v1 only support 'client_secret_basic'. For PKCE (none), use the v2 API. + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.description: Optional[str] = payload.get("description") + self.client_sid: Optional[str] = payload.get("client_sid") + self.token_endpoint_auth_method: Optional["OAuthAppInstance.str"] = ( + payload.get("token_endpoint_auth_method") + ) + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendoroauthappPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "owner_sid": self.owner_sid, + "description": self.description, + "client_sid": self.client_sid, + "token_endpoint_auth_method": self.token_endpoint_auth_method, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1AccountVendorOauthAppUpdateRequest(object): + """ + :ivar type: + :ivar friendly_name: + :ivar description: + :ivar policy: + :ivar access_token_ttl: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional[str] = payload.get("type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.policy: Optional[ + OAuthAppList.IamV1OrganizationVendorOauthAppUpdateRequestPolicy + ] = payload.get("policy") + self.access_token_ttl: Optional[int] = payload.get("access_token_ttl") + + def to_dict(self): + return { + "type": self.type, + "friendly_name": self.friendly_name, + "description": self.description, + "policy": self.policy.to_dict() if self.policy is not None else None, + "access_token_ttl": self.access_token_ttl, + } + + class IamV1OrganizationVendorOauthAppUpdateRequestPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + class IamV1OrganizationVendoroauthappPolicy(object): + """ + :ivar allow: Set of permissions explicitly allowed + :ivar deny: Set of permissions explicitly denied + """ + + def __init__(self, payload: Dict[str, Any]): + + self.allow: Optional[List[str]] = payload.get("allow") + self.deny: Optional[List[str]] = payload.get("deny") + + def to_dict(self): + return { + "allow": self.allow, + "deny": self.deny, + } + + def __init__(self, version: Version): + """ + Initialize the OAuthAppList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Account/OAuthApps" + + def _create( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> OAuthAppInstance: + """ + Create the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: The created OAuthAppInstance + """ + payload, _, _ = self._create( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + return OAuthAppInstance(self._version, payload) + + def create_with_http_info( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> ApiResponse: + """ + Create the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + instance = OAuthAppInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = iam_v1_account_vendor_oauth_app_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> OAuthAppInstance: + """ + Asynchronously create the OAuthAppInstance + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: The created OAuthAppInstance + """ + payload, _, _ = await self._create_async( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + return OAuthAppInstance(self._version, payload) + + async def create_with_http_info_async( + self, + iam_v1_account_vendor_oauth_app_create_request: IamV1AccountVendorOauthAppCreateRequest, + ) -> ApiResponse: + """ + Asynchronously create the OAuthAppInstance and return response metadata + + :param iam_v1_account_vendor_oauth_app_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + iam_v1_account_vendor_oauth_app_create_request=iam_v1_account_vendor_oauth_app_create_request + ) + instance = OAuthAppInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, sid: str) -> OAuthAppContext: + """ + Constructs a OAuthAppContext + + :param sid: Unique ID (sid) of the OAuth app + """ + return OAuthAppContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OAuthAppContext: + """ + Constructs a OAuthAppContext + + :param sid: Unique ID (sid) of the OAuth app + """ + return OAuthAppContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/role_permission.py b/twilio/rest/iam/v1/role_permission.py new file mode 100644 index 0000000000..833dafdf60 --- /dev/null +++ b/twilio/rest/iam/v1/role_permission.py @@ -0,0 +1,472 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RolePermissionInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Permission resource. + :ivar namespace: The namespace of the permission (e.g., twilio). + :ivar product: The product the permission belongs to (e.g., iam). + :ivar resource: The resource the permission applies to (e.g., roles). + :ivar action: The action granted by the permission (e.g., read). + :ivar external_description: The external description of the permission. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], role_sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.namespace: Optional[str] = payload.get("namespace") + self.product: Optional[str] = payload.get("product") + self.resource: Optional[str] = payload.get("resource") + self.action: Optional[str] = payload.get("action") + self.external_description: Optional[str] = payload.get("externalDescription") + + self._solution = { + "role_sid": role_sid or self.role_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RolePermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RolePermissionInstance: + """ + Build an instance of RolePermissionInstance + + :param payload: Payload response from the API + """ + + return RolePermissionInstance( + self._version, payload, role_sid=self._solution["role_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RolePermissionList(ListResource): + + def __init__(self, version: Version, role_sid: str): + """ + Initialize the RolePermissionList + + :param version: Version that contains the resource + :param role_sid: The SID of the Role for which Permissions will be fetched. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "role_sid": role_sid, + } + self._uri = "/Roles/{role_sid}/Permissions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RolePermissionInstance]: + """ + Streams RolePermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RolePermissionInstance]: + """ + Asynchronously streams RolePermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RolePermissionInstance]: + """ + Lists RolePermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RolePermissionInstance]: + """ + Asynchronously lists RolePermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RolePermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePermissionPage: + """ + Retrieve a single page of RolePermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RolePermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePermissionPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePermissionPage: + """ + Asynchronously retrieve a single page of RolePermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RolePermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RolePermissionPage: + """ + Retrieve a specific page of RolePermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RolePermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePermissionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RolePermissionPage: + """ + Asynchronously retrieve a specific page of RolePermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RolePermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePermissionPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/token.py b/twilio/rest/iam/v1/token.py new file mode 100644 index 0000000000..72d5da3fe9 --- /dev/null +++ b/twilio/rest/iam/v1/token.py @@ -0,0 +1,301 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def _create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + payload, _, _ = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/InsightsBase.py b/twilio/rest/insights/InsightsBase.py index 458122cec7..e2d5c3328d 100644 --- a/twilio/rest/insights/InsightsBase.py +++ b/twilio/rest/insights/InsightsBase.py @@ -14,6 +14,8 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.insights.v1 import V1 +from twilio.rest.insights.v2 import V2 +from twilio.rest.insights.v3 import V3 class InsightsBase(Domain): @@ -26,6 +28,8 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://insights.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -36,6 +40,24 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Insights + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Insights + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/insights/v1/call/__init__.py b/twilio/rest/insights/v1/call/__init__.py index cb08aa58aa..89516703cd 100644 --- a/twilio/rest/insights/v1/call/__init__.py +++ b/twilio/rest/insights/v1/call/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "CallInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def annotation(self) -> AnnotationList: """ @@ -139,48 +159,96 @@ def __init__(self, version: Version, sid: str): self._events: Optional[EventList] = None self._metrics: Optional[MetricList] = None - def fetch(self) -> CallInstance: + def _fetch(self) -> tuple: """ - Fetch the CallInstance + Internal helper for fetch operation - - :returns: The fetched CallInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + payload, _, _ = self._fetch() return CallInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CallInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CallInstance + Fetch the CallInstance and return response metadata - :returns: The fetched CallInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + payload, _, _ = await self._fetch_async() return CallInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def annotation(self) -> AnnotationList: """ diff --git a/twilio/rest/insights/v1/call/annotation.py b/twilio/rest/insights/v1/call/annotation.py index 6e705d3916..5bda909b68 100644 --- a/twilio/rest/insights/v1/call/annotation.py +++ b/twilio/rest/insights/v1/call/annotation.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self._solution = { "call_sid": call_sid, } + self._context: Optional[AnnotationContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "AnnotationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, @@ -174,6 +194,76 @@ async def update_async( incident=incident, ) + def update_with_http_info( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AnnotationInstance with HTTP info + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + async def update_with_http_info_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AnnotationInstance with HTTP info + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,49 +291,97 @@ def __init__(self, version: Version, call_sid: str): } self._uri = "/Voice/{call_sid}/Annotation".format(**self._solution) - def fetch(self) -> AnnotationInstance: + def _fetch(self) -> tuple: """ - Fetch the AnnotationInstance + Internal helper for fetch operation - - :returns: The fetched AnnotationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AnnotationInstance: + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + payload, _, _ = self._fetch() return AnnotationInstance( self._version, payload, call_sid=self._solution["call_sid"], ) - async def fetch_async(self) -> AnnotationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AnnotationInstance + Fetch the AnnotationInstance and return response metadata - :returns: The fetched AnnotationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AnnotationInstance: + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + payload, _, _ = await self._fetch_async() return AnnotationInstance( self._version, payload, call_sid=self._solution["call_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AnnotationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, connectivity_issue: Union[ @@ -254,19 +392,12 @@ def update( call_score: Union[int, object] = values.unset, comment: Union[str, object] = values.unset, incident: Union[str, object] = values.unset, - ) -> AnnotationInstance: + ) -> tuple: """ - Update the AnnotationInstance + Internal helper for update operation - :param answered_by: - :param connectivity_issue: - :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. - :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. - :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. - :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. - :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. - - :returns: The updated AnnotationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -286,15 +417,49 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + payload, _, _ = self._update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) return AnnotationInstance( self._version, payload, call_sid=self._solution["call_sid"] ) - async def update_async( + def update_with_http_info( self, answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, connectivity_issue: Union[ @@ -305,9 +470,9 @@ async def update_async( call_score: Union[int, object] = values.unset, comment: Union[str, object] = values.unset, incident: Union[str, object] = values.unset, - ) -> AnnotationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AnnotationInstance + Update the AnnotationInstance and return response metadata :param answered_by: :param connectivity_issue: @@ -317,7 +482,39 @@ async def update_async( :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. - :returns: The updated AnnotationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + instance = AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -337,14 +534,87 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Asynchronous coroutine to update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + payload, _, _ = await self._update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) return AnnotationInstance( self._version, payload, call_sid=self._solution["call_sid"] ) + async def update_with_http_info_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AnnotationInstance and return response metadata + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + instance = AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/insights/v1/call/call_summary.py b/twilio/rest/insights/v1/call/call_summary.py index e21af100a1..4d1e0d94de 100644 --- a/twilio/rest/insights/v1/call/call_summary.py +++ b/twilio/rest/insights/v1/call/call_summary.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +24,12 @@ class CallSummaryInstance(InstanceResource): + class CallSummaryCrelaySessionState(object): + UNKNOWN = "unknown" + FAILURE = "failure" + ENDED = "ended" + HUNG_UP = "hung_up" + class AnsweredBy(object): UNKNOWN = "unknown" MACHINE_START = "machine_start" @@ -65,18 +72,19 @@ class ProcessingState(object): :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. :ivar duration: Duration between when the call was initiated and the call was ended :ivar connect_duration: Duration between when the call was answered and when it ended - :ivar _from: The calling party. - :ivar to: The called party. - :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. - :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. - :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. - :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar _from: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. :ivar url: The URL of this resource. - :ivar attributes: Attributes capturing call-flow-specific details. - :ivar properties: Contains edge-agnostic call-level details. - :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. - :ivar annotation: Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. + :ivar attributes: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + :ivar agent_session_summaries: `object` List of session summaries for conversation relay. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#conversation-relay-object) for the object properties. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -121,10 +129,14 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self.properties: Optional[Dict[str, object]] = payload.get("properties") self.trust: Optional[Dict[str, object]] = payload.get("trust") self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + self.agent_session_summaries: Optional[List[str]] = payload.get( + "agent_session_summaries" + ) self._solution = { "call_sid": call_sid, } + self._context: Optional[CallSummaryContext] = None @property @@ -176,6 +188,40 @@ async def fetch_async( processing_state=processing_state, ) + def fetch_with_http_info( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Fetch the CallSummaryInstance with HTTP info + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + processing_state=processing_state, + ) + + async def fetch_with_http_info_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallSummaryInstance with HTTP info + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + processing_state=processing_state, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,21 +249,20 @@ def __init__(self, version: Version, call_sid: str): } self._uri = "/Voice/{call_sid}/Summary".format(**self._solution) - def fetch( + def _fetch( self, processing_state: Union[ "CallSummaryInstance.ProcessingState", object ] = values.unset, - ) -> CallSummaryInstance: + ) -> tuple: """ - Fetch the CallSummaryInstance - - :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + Internal helper for fetch operation - :returns: The fetched CallSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "ProcessingState": processing_state, } @@ -227,31 +272,65 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + payload, _, _ = self._fetch(processing_state=processing_state) return CallSummaryInstance( self._version, payload, call_sid=self._solution["call_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, processing_state: Union[ "CallSummaryInstance.ProcessingState", object ] = values.unset, - ) -> CallSummaryInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the CallSummaryInstance + Fetch the CallSummaryInstance and return response metadata :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. - :returns: The fetched CallSummaryInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch(processing_state=processing_state) + instance = CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "ProcessingState": processing_state, } @@ -261,16 +340,53 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Asynchronous coroutine to fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + payload, _, _ = await self._fetch_async(processing_state=processing_state) return CallSummaryInstance( self._version, payload, call_sid=self._solution["call_sid"], ) + async def fetch_with_http_info_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallSummaryInstance and return response metadata + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + processing_state=processing_state + ) + instance = CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/insights/v1/call/event.py b/twilio/rest/insights/v1/call/event.py index 98dce5eb71..68f4893cd1 100644 --- a/twilio/rest/insights/v1/call/event.py +++ b/twilio/rest/insights/v1/call/event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,10 +46,11 @@ class TwilioEdge(object): :ivar group: Event group. :ivar level: :ivar name: Event name. - :ivar carrier_edge: Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. - :ivar sip_edge: Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. - :ivar sdk_edge: Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. - :ivar client_edge: Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. + :ivar carrier_edge: `object` Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar conversation_relay_data: """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -65,6 +67,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + self.conversation_relay_data: Optional[str] = payload.get( + "conversation_relay_data" + ) self._solution = { "call_sid": call_sid, @@ -88,6 +93,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -173,6 +179,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + edge=edge, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + edge=edge, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, edge: Union["EventInstance.TwilioEdge", object] = values.unset, @@ -194,6 +256,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -223,6 +286,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -232,6 +296,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + edge=edge, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + edge=edge, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, edge: Union["EventInstance.TwilioEdge", object] = values.unset, @@ -266,7 +386,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -302,7 +422,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EventPage: """ @@ -314,7 +510,7 @@ def get_page(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EventPage: """ @@ -326,7 +522,7 @@ async def get_page_async(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/insights/v1/call/metric.py b/twilio/rest/insights/v1/call/metric.py index 77f770ae7c..7cf72240b7 100644 --- a/twilio/rest/insights/v1/call/metric.py +++ b/twilio/rest/insights/v1/call/metric.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: :param payload: Payload response from the API """ + return MetricInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -176,6 +178,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, edge: Union["MetricInstance.TwilioEdge", object] = values.unset, @@ -199,6 +261,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -231,6 +294,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -241,6 +305,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, edge: Union["MetricInstance.TwilioEdge", object] = values.unset, @@ -278,7 +404,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MetricPage(self._version, response, self._solution) + return MetricPage(self._version, response, solution=self._solution) async def page_async( self, @@ -317,7 +443,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MetricPage(self._version, response, self._solution) + return MetricPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MetricPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MetricPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MetricPage, status code, and headers + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MetricPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MetricPage: """ @@ -329,7 +537,7 @@ def get_page(self, target_url: str) -> MetricPage: :returns: Page of MetricInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MetricPage(self._version, response, self._solution) + return MetricPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MetricPage: """ @@ -341,7 +549,7 @@ async def get_page_async(self, target_url: str) -> MetricPage: :returns: Page of MetricInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MetricPage(self._version, response, self._solution) + return MetricPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/insights/v1/call_summaries.py b/twilio/rest/insights/v1/call_summaries.py index 0a75e38454..1f66d767ef 100644 --- a/twilio/rest/insights/v1/call_summaries.py +++ b/twilio/rest/insights/v1/call_summaries.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,12 @@ class SortBy(object): START_TIME = "start_time" END_TIME = "end_time" + class CallSummaryCrelaySessionState(object): + UNKNOWN = "unknown" + FAILURE = "failure" + ENDED = "ended" + HUNG_UP = "hung_up" + """ :ivar account_sid: The unique SID identifier of the Account. :ivar call_sid: The unique SID identifier of the Call. @@ -76,18 +83,19 @@ class SortBy(object): :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. :ivar duration: Duration between when the call was initiated and the call was ended :ivar connect_duration: Duration between when the call was answered and when it ended - :ivar _from: The calling party. - :ivar to: The called party. - :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. - :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. - :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. - :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar _from: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. :ivar url: The URL of this resource. - :ivar attributes: Attributes capturing call-flow-specific details. - :ivar properties: Contains edge-agnostic call-level details. - :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. - :ivar annotation: + :ivar attributes: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. + :ivar agent_session_summaries: `array[object]` List of agent session summaries for conversation relay. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#conversation-relay-object) for the object properties. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -132,6 +140,9 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.properties: Optional[Dict[str, object]] = payload.get("properties") self.trust: Optional[Dict[str, object]] = payload.get("trust") self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + self.agent_session_summaries: Optional[List[str]] = payload.get( + "agent_session_summaries" + ) def __repr__(self) -> str: """ @@ -151,6 +162,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CallSummariesInstance: :param payload: Payload response from the API """ + return CallSummariesInstance(self._version, payload) def __repr__(self) -> str: @@ -205,6 +217,10 @@ def stream( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, @@ -246,6 +262,10 @@ def stream( :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -289,6 +309,10 @@ def stream( branded_enabled=branded_enabled, voice_integrity_enabled=voice_integrity_enabled, branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, voice_integrity_bundle_sid=voice_integrity_bundle_sid, voice_integrity_use_case=voice_integrity_use_case, business_profile_identity=business_profile_identity, @@ -330,6 +354,10 @@ async def stream_async( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, @@ -371,6 +399,10 @@ async def stream_async( :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -414,6 +446,10 @@ async def stream_async( branded_enabled=branded_enabled, voice_integrity_enabled=voice_integrity_enabled, branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, voice_integrity_bundle_sid=voice_integrity_bundle_sid, voice_integrity_use_case=voice_integrity_use_case, business_profile_identity=business_profile_identity, @@ -425,6 +461,278 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CallSummariesInstance and returns headers from first page + + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CallSummariesInstance and returns headers from first page + + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, from_: Union[str, object] = values.unset, @@ -455,6 +763,10 @@ def list( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, @@ -495,6 +807,10 @@ def list( :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -510,6 +826,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( from_=from_, @@ -538,6 +855,10 @@ def list( branded_enabled=branded_enabled, voice_integrity_enabled=voice_integrity_enabled, branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, voice_integrity_bundle_sid=voice_integrity_bundle_sid, voice_integrity_use_case=voice_integrity_use_case, business_profile_identity=business_profile_identity, @@ -579,6 +900,10 @@ async def list_async( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, @@ -619,6 +944,10 @@ async def list_async( :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -634,6 +963,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -663,6 +993,10 @@ async def list_async( branded_enabled=branded_enabled, voice_integrity_enabled=voice_integrity_enabled, branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, voice_integrity_bundle_sid=voice_integrity_bundle_sid, voice_integrity_use_case=voice_integrity_use_case, business_profile_identity=business_profile_identity, @@ -674,7 +1008,7 @@ async def list_async( ) ] - def page( + def list_with_http_info( self, from_: Union[str, object] = values.unset, to: Union[str, object] = values.unset, @@ -704,27 +1038,301 @@ def page( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, business_profile_industry: Union[str, object] = values.unset, business_profile_bundle_sid: Union[str, object] = values.unset, business_profile_type: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> CallSummariesPage: + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: """ - Retrieve a single page of CallSummariesInstance records from the API. - Request is executed immediately + Lists CallSummariesInstance and returns headers from first page - :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. - :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. - :param from_carrier: An origination carrier. - :param to_carrier: A destination carrier. - :param from_country_code: A source country code based on phone number in From. - :param to_country_code: A destination country code. Based on phone number in To. - :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CallSummariesInstance and returns headers from first page + + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. @@ -744,6 +1352,10 @@ def page( :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -786,6 +1398,10 @@ def page( voice_integrity_enabled ), "BrandedBundleSid": branded_bundle_sid, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, "VoiceIntegrityUseCase": voice_integrity_use_case, "BusinessProfileIdentity": business_profile_identity, @@ -837,6 +1453,10 @@ async def page_async( branded_enabled: Union[bool, object] = values.unset, voice_integrity_enabled: Union[bool, object] = values.unset, branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, voice_integrity_bundle_sid: Union[str, object] = values.unset, voice_integrity_use_case: Union[str, object] = values.unset, business_profile_identity: Union[str, object] = values.unset, @@ -877,6 +1497,10 @@ async def page_async( :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. @@ -919,6 +1543,10 @@ async def page_async( voice_integrity_enabled ), "BrandedBundleSid": branded_bundle_sid, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, "VoiceIntegrityUseCase": voice_integrity_use_case, "BusinessProfileIdentity": business_profile_identity, @@ -940,6 +1568,300 @@ async def page_async( ) return CallSummariesPage(self._version, response) + def page_with_http_info( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CallSummariesPage, status code, and headers + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CallSummariesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CallSummariesPage, status code, and headers + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "BrandedLogo": serialize.boolean_to_string(branded_logo), + "BrandedType": branded_type, + "BrandedUseCase": branded_use_case, + "BrandedCallReason": branded_call_reason, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CallSummariesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CallSummariesPage: """ Retrieve a specific page of CallSummariesInstance records from the API. diff --git a/twilio/rest/insights/v1/conference/__init__.py b/twilio/rest/insights/v1/conference/__init__.py index 0f9bb118b5..72a54a8e96 100644 --- a/twilio/rest/insights/v1/conference/__init__.py +++ b/twilio/rest/insights/v1/conference/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,12 +52,14 @@ class ProcessingState(object): class Region(object): US1 = "us1" + US2 = "us2" AU1 = "au1" BR1 = "br1" IE1 = "ie1" JP1 = "jp1" SG1 = "sg1" DE1 = "de1" + IN1 = "in1" class Tag(object): INVALID_REQUESTED_REGION = "invalid_requested_region" @@ -161,6 +164,7 @@ def __init__( self._solution = { "conference_sid": conference_sid or self.conference_sid, } + self._context: Optional[ConferenceContext] = None @property @@ -196,6 +200,24 @@ async def fetch_async(self) -> "ConferenceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def conference_participants(self) -> ConferenceParticipantList: """ @@ -232,48 +254,96 @@ def __init__(self, version: Version, conference_sid: str): self._conference_participants: Optional[ConferenceParticipantList] = None - def fetch(self) -> ConferenceInstance: + def _fetch(self) -> tuple: """ - Fetch the ConferenceInstance - + Internal helper for fetch operation - :returns: The fetched ConferenceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = self._fetch() return ConferenceInstance( self._version, payload, conference_sid=self._solution["conference_sid"], ) - async def fetch_async(self) -> ConferenceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConferenceInstance + Fetch the ConferenceInstance and return response metadata - :returns: The fetched ConferenceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + payload, _, _ = await self._fetch_async() return ConferenceInstance( self._version, payload, conference_sid=self._solution["conference_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def conference_participants(self) -> ConferenceParticipantList: """ @@ -304,6 +374,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: :param payload: Payload response from the API """ + return ConferenceInstance(self._version, payload) def __repr__(self) -> str: @@ -442,6 +513,118 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConferenceInstance and returns headers from first page + + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConferenceInstance and returns headers from first page + + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, conference_sid: Union[str, object] = values.unset, @@ -481,6 +664,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( conference_sid=conference_sid, @@ -537,6 +721,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -555,6 +740,116 @@ async def list_async( ) ] + def list_with_http_info( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConferenceInstance and returns headers from first page + + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceInstance and returns headers from first page + + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, conference_sid: Union[str, object] = values.unset, @@ -681,6 +976,136 @@ async def page_async( ) return ConferencePage(self._version, response) + def page_with_http_info( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferencePage, status code, and headers + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferencePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferencePage, status code, and headers + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferencePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ConferencePage: """ Retrieve a specific page of ConferenceInstance records from the API. diff --git a/twilio/rest/insights/v1/conference/conference_participant.py b/twilio/rest/insights/v1/conference/conference_participant.py index 203f950699..ce953db174 100644 --- a/twilio/rest/insights/v1/conference/conference_participant.py +++ b/twilio/rest/insights/v1/conference/conference_participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ class Region(object): JP1 = "jp1" SG1 = "sg1" DE1 = "de1" + IN1 = "in1" """ :ivar participant_sid: SID for this participant. @@ -160,6 +162,7 @@ def __init__( "conference_sid": conference_sid, "participant_sid": participant_sid or self.participant_sid, } + self._context: Optional[ConferenceParticipantContext] = None @property @@ -214,6 +217,42 @@ async def fetch_async( metrics=metrics, ) + def fetch_with_http_info( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + events=events, + metrics=metrics, + ) + + async def fetch_with_http_info_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + events=events, + metrics=metrics, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,21 +286,19 @@ def __init__(self, version: Version, conference_sid: str, participant_sid: str): ) ) - def fetch( + def _fetch( self, events: Union[str, object] = values.unset, metrics: Union[str, object] = values.unset, - ) -> ConferenceParticipantInstance: + ) -> tuple: """ - Fetch the ConferenceParticipantInstance + Internal helper for fetch operation - :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. - :param metrics: Object. Contains participant call quality metrics. - - :returns: The fetched ConferenceParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Events": events, "Metrics": metrics, @@ -272,10 +309,24 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + payload, _, _ = self._fetch(events=events, metrics=metrics) return ConferenceParticipantInstance( self._version, payload, @@ -283,21 +334,41 @@ def fetch( participant_sid=self._solution["participant_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, events: Union[str, object] = values.unset, metrics: Union[str, object] = values.unset, - ) -> ConferenceParticipantInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConferenceParticipantInstance + Fetch the ConferenceParticipantInstance and return response metadata :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. :param metrics: Object. Contains participant call quality metrics. - :returns: The fetched ConferenceParticipantInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch(events=events, metrics=metrics) + instance = ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Events": events, "Metrics": metrics, @@ -308,10 +379,24 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + payload, _, _ = await self._fetch_async(events=events, metrics=metrics) return ConferenceParticipantInstance( self._version, payload, @@ -319,6 +404,30 @@ async def fetch_async( participant_sid=self._solution["participant_sid"], ) + async def fetch_with_http_info_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance and return response metadata + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + events=events, metrics=metrics + ) + instance = ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -337,6 +446,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceParticipantInstance :param payload: Payload response from the API """ + return ConferenceParticipantInstance( self._version, payload, conference_sid=self._solution["conference_sid"] ) @@ -442,6 +552,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConferenceParticipantInstance and returns headers from first page + + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConferenceParticipantInstance and returns headers from first page + + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, participant_sid: Union[str, object] = values.unset, @@ -467,6 +647,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( participant_sid=participant_sid, @@ -502,6 +683,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -513,6 +695,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConferenceParticipantInstance and returns headers from first page + + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConferenceParticipantInstance and returns headers from first page + + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, participant_sid: Union[str, object] = values.unset, @@ -553,7 +803,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConferenceParticipantPage(self._version, response, self._solution) + return ConferenceParticipantPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -595,7 +847,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConferenceParticipantPage(self._version, response, self._solution) + return ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConferenceParticipantPage: """ @@ -607,7 +953,9 @@ def get_page(self, target_url: str) -> ConferenceParticipantPage: :returns: Page of ConferenceParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConferenceParticipantPage(self._version, response, self._solution) + return ConferenceParticipantPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> ConferenceParticipantPage: """ @@ -619,7 +967,9 @@ async def get_page_async(self, target_url: str) -> ConferenceParticipantPage: :returns: Page of ConferenceParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConferenceParticipantPage(self._version, response, self._solution) + return ConferenceParticipantPage( + self._version, response, solution=self._solution + ) def get(self, participant_sid: str) -> ConferenceParticipantContext: """ diff --git a/twilio/rest/insights/v1/room/__init__.py b/twilio/rest/insights/v1/room/__init__.py index 0b987c020a..c754e43850 100644 --- a/twilio/rest/insights/v1/room/__init__.py +++ b/twilio/rest/insights/v1/room/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,8 @@ class EndReason(object): class ProcessingState(object): COMPLETE = "complete" IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + NOT_STARTED = "not_started" class RoomStatus(object): IN_PROGRESS = "in_progress" @@ -76,8 +79,6 @@ class TwilioRealm(object): IN1 = "in1" DE1 = "de1" GLL = "gll" - STAGE_US1 = "stage_us1" - DEV_US1 = "dev_us1" """ :ivar account_sid: Account SID associated with this room. @@ -173,6 +174,7 @@ def __init__( self._solution = { "room_sid": room_sid or self.room_sid, } + self._context: Optional[RoomContext] = None @property @@ -208,6 +210,24 @@ async def fetch_async(self) -> "RoomInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def participants(self) -> ParticipantList: """ @@ -244,48 +264,96 @@ def __init__(self, version: Version, room_sid: str): self._participants: Optional[ParticipantList] = None - def fetch(self) -> RoomInstance: + def _fetch(self) -> tuple: """ - Fetch the RoomInstance - + Internal helper for fetch operation - :returns: The fetched RoomInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + :returns: The fetched RoomInstance + """ + payload, _, _ = self._fetch() return RoomInstance( self._version, payload, room_sid=self._solution["room_sid"], ) - async def fetch_async(self) -> RoomInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoomInstance + Fetch the RoomInstance and return response metadata - :returns: The fetched RoomInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + payload, _, _ = await self._fetch_async() return RoomInstance( self._version, payload, room_sid=self._solution["room_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def participants(self) -> ParticipantList: """ @@ -316,6 +384,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -424,6 +493,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoomInstance and returns headers from first page + + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoomInstance and returns headers from first page + + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, @@ -453,6 +604,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( room_type=room_type, @@ -494,6 +646,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -507,6 +660,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoomInstance and returns headers from first page + + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoomInstance and returns headers from first page + + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, @@ -603,6 +836,106 @@ async def page_async( ) return RoomPage(self._version, response) + def page_with_http_info( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomPage, status code, and headers + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomPage, status code, and headers + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RoomPage: """ Retrieve a specific page of RoomInstance records from the API. diff --git a/twilio/rest/insights/v1/room/participant.py b/twilio/rest/insights/v1/room/participant.py index 0791ec287c..9ae8554b95 100644 --- a/twilio/rest/insights/v1/room/participant.py +++ b/twilio/rest/insights/v1/room/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -43,7 +44,9 @@ class EdgeLocation(object): class RoomStatus(object): IN_PROGRESS = "in_progress" + CONNECTED = "connected" COMPLETED = "completed" + DISCONNECTED = "disconnected" class TwilioRealm(object): US1 = "us1" @@ -56,8 +59,6 @@ class TwilioRealm(object): IN1 = "in1" DE1 = "de1" GLL = "gll" - STAGE_US1 = "stage_us1" - DEV_US1 = "dev_us1" """ :ivar participant_sid: Unique identifier for the participant. @@ -118,6 +119,7 @@ def __init__( "room_sid": room_sid, "participant_sid": participant_sid or self.participant_sid, } + self._context: Optional[ParticipantContext] = None @property @@ -154,6 +156,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -185,20 +205,30 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str): **self._solution ) - def fetch(self) -> ParticipantInstance: + def _fetch(self) -> tuple: """ - Fetch the ParticipantInstance - + Internal helper for fetch operation - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -206,22 +236,46 @@ def fetch(self) -> ParticipantInstance: participant_sid=self._solution["participant_sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -229,6 +283,22 @@ async def fetch_async(self) -> ParticipantInstance: participant_sid=self._solution["participant_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,6 +317,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -328,6 +399,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -347,6 +468,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -373,6 +495,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -381,6 +504,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -412,7 +585,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -445,7 +618,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -457,7 +700,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -469,7 +712,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, participant_sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/insights/v1/setting.py b/twilio/rest/insights/v1/setting.py index 3c6b746f07..daf49229a9 100644 --- a/twilio/rest/insights/v1/setting.py +++ b/twilio/rest/insights/v1/setting.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,34 @@ async def fetch_async( subaccount_sid=subaccount_sid, ) + def fetch_with_http_info( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + subaccount_sid=subaccount_sid, + ) + + async def fetch_with_http_info_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + subaccount_sid=subaccount_sid, + ) + def update( self, advanced_features: Union[bool, object] = values.unset, @@ -122,6 +151,48 @@ async def update_async( subaccount_sid=subaccount_sid, ) + def update_with_http_info( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SettingInstance with HTTP info + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + async def update_with_http_info_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingInstance with HTTP info + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -144,18 +215,15 @@ def __init__(self, version: Version): self._uri = "/Voice/Settings" - def fetch( - self, subaccount_sid: Union[str, object] = values.unset - ) -> SettingInstance: + def _fetch(self, subaccount_sid: Union[str, object] = values.unset) -> tuple: """ - Fetch the SettingInstance + Internal helper for fetch operation - :param subaccount_sid: The unique SID identifier of the Subaccount. - - :returns: The fetched SettingInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "SubaccountSid": subaccount_sid, } @@ -165,27 +233,54 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + payload, _, _ = self._fetch(subaccount_sid=subaccount_sid) return SettingInstance( self._version, payload, ) - async def fetch_async( + def fetch_with_http_info( self, subaccount_sid: Union[str, object] = values.unset - ) -> SettingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the SettingInstance + Fetch the SettingInstance and return response metadata :param subaccount_sid: The unique SID identifier of the Subaccount. - :returns: The fetched SettingInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch(subaccount_sid=subaccount_sid) + instance = SettingInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "SubaccountSid": subaccount_sid, } @@ -195,29 +290,56 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Asynchronous coroutine to fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + payload, _, _ = await self._fetch_async(subaccount_sid=subaccount_sid) return SettingInstance( self._version, payload, ) - def update( + async def fetch_with_http_info_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingInstance and return response metadata + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + subaccount_sid=subaccount_sid + ) + instance = SettingInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, advanced_features: Union[bool, object] = values.unset, voice_trace: Union[bool, object] = values.unset, subaccount_sid: Union[str, object] = values.unset, - ) -> SettingInstance: + ) -> tuple: """ - Update the SettingInstance + Internal helper for update operation - :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. - :param voice_trace: A boolean flag to enable Voice Trace. - :param subaccount_sid: The unique SID identifier of the Subaccount. - - :returns: The updated SettingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -233,20 +355,18 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SettingInstance(self._version, payload) - - async def update_async( + def update( self, advanced_features: Union[bool, object] = values.unset, voice_trace: Union[bool, object] = values.unset, subaccount_sid: Union[str, object] = values.unset, ) -> SettingInstance: """ - Asynchronous coroutine to update the SettingInstance + Update the SettingInstance :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. :param voice_trace: A boolean flag to enable Voice Trace. @@ -254,6 +374,48 @@ async def update_async( :returns: The updated SettingInstance """ + payload, _, _ = self._update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + return SettingInstance(self._version, payload) + + def update_with_http_info( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SettingInstance and return response metadata + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + instance = SettingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -268,12 +430,55 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> SettingInstance: + """ + Asynchronous coroutine to update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + payload, _, _ = await self._update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) return SettingInstance(self._version, payload) + async def update_with_http_info_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingInstance and return response metadata + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + instance = SettingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/insights/v2/__init__.py b/twilio/rest/insights/v2/__init__.py new file mode 100644 index 0000000000..9f2e26d1f0 --- /dev/null +++ b/twilio/rest/insights/v2/__init__.py @@ -0,0 +1,73 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.insights.v2.inbound import InboundList +from twilio.rest.insights.v2.outbound import OutboundList +from twilio.rest.insights.v2.report import ReportList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v2") + self._reports: Optional[ReportList] = None + + def inbound(self, report_id: str, inbound_id: str = None): + """ + Access the InboundList resource + + :param report_id: A unique Report Id. + + :param inbound_id: Optional instance ID to directly access InboundContext + :returns: InboundList instance if inbound_id is None, otherwise InboundContext + """ + list_instance = InboundList(self, report_id) + if inbound_id is not None: + return list_instance(inbound_id) + return list_instance + + def outbound(self, report_id: str, outbound_id: str = None): + """ + Access the OutboundList resource + + :param report_id: A unique Report Id. + + :param outbound_id: Optional instance ID to directly access OutboundContext + :returns: OutboundList instance if outbound_id is None, otherwise OutboundContext + """ + list_instance = OutboundList(self, report_id) + if outbound_id is not None: + return list_instance(outbound_id) + return list_instance + + @property + def reports(self) -> ReportList: + if self._reports is None: + self._reports = ReportList(self) + return self._reports + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/inbound.py b/twilio/rest/insights/v2/inbound.py new file mode 100644 index 0000000000..47bf2a0266 --- /dev/null +++ b/twilio/rest/insights/v2/inbound.py @@ -0,0 +1,1124 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InboundInstance(InstanceResource): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[InboundContext] = None + + @property + def _proxy(self) -> "InboundContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InboundContext for this InboundInstance + """ + if self._context is None: + self._context = InboundContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "InboundInstance": + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + return self._proxy.create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "InboundInstance": + """ + Asynchronous coroutine to create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + return await self._proxy.create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InboundContext(InstanceContext): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the InboundContext + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Inbound".format(**self._solution) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Asynchronous coroutine to create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InboundPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InboundInstance: + """ + Build an instance of InboundInstance + + :param payload: Payload response from the API + """ + + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InboundList(ListResource): + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the InboundList + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Inbound/{report_id}".format( + **self._solution + ) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> InboundInstance: + """ + Asynchronously create the InboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created InboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = InboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InboundInstance]: + """ + Streams InboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InboundInstance]: + """ + Asynchronously streams InboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InboundInstance]: + """ + Lists InboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InboundInstance]: + """ + Asynchronously lists InboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InboundPage: + """ + Retrieve a single page of InboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InboundPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InboundPage: + """ + Asynchronously retrieve a single page of InboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InboundPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> InboundPage: + """ + Retrieve a specific page of InboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InboundInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InboundPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> InboundPage: + """ + Asynchronously retrieve a specific page of InboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InboundInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InboundPage(self._version, response, solution=self._solution) + + def get(self, report_id: str) -> InboundContext: + """ + Constructs a InboundContext + + :param report_id: A unique Report Id. + """ + return InboundContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> InboundContext: + """ + Constructs a InboundContext + + :param report_id: A unique Report Id. + """ + return InboundContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/outbound.py b/twilio/rest/insights/v2/outbound.py new file mode 100644 index 0000000000..2774a09d08 --- /dev/null +++ b/twilio/rest/insights/v2/outbound.py @@ -0,0 +1,1227 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OutboundInstance(InstanceResource): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + :ivar calls_by_device_type: Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar answer_rate_device_type: Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar answering_machine_detection: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + self.calls_by_device_type: Optional[Dict[str, int]] = payload.get( + "calls_by_device_type" + ) + self.answer_rate_device_type: Optional[Dict[str, float]] = payload.get( + "answer_rate_device_type" + ) + self.blocked_calls_by_carrier: Optional[List[str]] = payload.get( + "blocked_calls_by_carrier" + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.answering_machine_detection: Optional[str] = payload.get( + "answering_machine_detection" + ) + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[OutboundContext] = None + + @property + def _proxy(self) -> "OutboundContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OutboundContext for this OutboundInstance + """ + if self._context is None: + self._context = OutboundContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "OutboundInstance": + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + return self._proxy.create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> "OutboundInstance": + """ + Asynchronous coroutine to create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + return await self._proxy.create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the OutboundInstance with HTTP info + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OutboundContext(InstanceContext): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the OutboundContext + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Outbound".format(**self._solution) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Asynchronous coroutine to create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OutboundPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OutboundInstance: + """ + Build an instance of OutboundInstance + + :param payload: Payload response from the API + """ + + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OutboundList(ListResource): + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreatePhoneNumbersReportRequest(object): + """ + :ivar time_range: + :ivar filters: + :ivar size: The number of max available top Phone Numbers to generate. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + InboundList.InsightsV2CreatePhoneNumbersReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[InboundList.PhoneNumberReportFilter]] = ( + payload.get("filters") + ) + self.size: Optional[int] = payload.get("size") + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "size": self.size, + } + + class InsightsV2CreatePhoneNumbersReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class PhoneNumberReportFilter(object): + """ + :ivar key: The name of the filter + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the OutboundList + + :param version: Version that contains the resource + :param report_id: A unique Report Id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/PhoneNumbers/Outbound/{report_id}".format( + **self._solution + ) + + def _create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_phone_numbers_report_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> OutboundInstance: + """ + Asynchronously create the OutboundInstance + + :param insights_v2_create_phone_numbers_report_request: + + :returns: The created OutboundInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + return OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_phone_numbers_report_request: Union[ + InsightsV2CreatePhoneNumbersReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the OutboundInstance and return response metadata + + :param insights_v2_create_phone_numbers_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_phone_numbers_report_request=insights_v2_create_phone_numbers_report_request + ) + instance = OutboundInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OutboundInstance]: + """ + Streams OutboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OutboundInstance]: + """ + Asynchronously streams OutboundInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutboundInstance]: + """ + Lists OutboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutboundInstance]: + """ + Asynchronously lists OutboundInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OutboundInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutboundPage: + """ + Retrieve a single page of OutboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutboundPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutboundPage: + """ + Asynchronously retrieve a single page of OutboundInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutboundInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutboundPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OutboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OutboundPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OutboundPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> OutboundPage: + """ + Retrieve a specific page of OutboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutboundInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OutboundPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> OutboundPage: + """ + Asynchronously retrieve a specific page of OutboundInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutboundInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OutboundPage(self._version, response, solution=self._solution) + + def get(self, report_id: str) -> OutboundContext: + """ + Constructs a OutboundContext + + :param report_id: A unique Report Id. + """ + return OutboundContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> OutboundContext: + """ + Constructs a OutboundContext + + :param report_id: A unique Report Id. + """ + return OutboundContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v2/report.py b/twilio/rest/insights/v2/report.py new file mode 100644 index 0000000000..fb7df212e9 --- /dev/null +++ b/twilio/rest/insights/v2/report.py @@ -0,0 +1,2199 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Sample/reference Twilio API. + This is the reference API for the rest-proxy server. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ReportInstance(InstanceResource): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + class ReportStatus(object): + CREATED = "created" + RUNNING = "running" + COMPLETED = "completed" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar report_id: The report identifier as Voice Insights Report TTID. + :ivar status: + :ivar request_meta: + :ivar url: The URL of this resource. + :ivar handle: Inbound phone number handle represented in the report. + :ivar total_calls: Total number of calls made with the given handle during the report period. + :ivar call_answer_score: The call answer score measures customers behavior to the delivered calls. The score is a value between 0 and 100, where 100 indicates that all calls were successfully answered. + :ivar call_state_percentage: + :ivar silent_calls_percentage: Percentage of inbound calls with silence tags over total outbound calls. A silent tag is indicative of a connectivity issue or muted audio. + :ivar calls_by_device_type: Number of calls made with each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar answer_rate_device_type: Answer rate for each device type. `voip`, `mobile`, `landline`, `unknown` + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar answering_machine_detection: + :ivar report: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], report_id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.report_id: Optional[str] = payload.get("report_id") + self.status: Optional["InboundInstance.str"] = payload.get("status") + self.request_meta: Optional[str] = payload.get("request_meta") + self.url: Optional[str] = payload.get("url") + self.handle: Optional[str] = payload.get("handle") + self.total_calls: Optional[int] = deserialize.integer( + payload.get("total_calls") + ) + self.call_answer_score: Optional[float] = payload.get("call_answer_score") + self.call_state_percentage: Optional[str] = payload.get("call_state_percentage") + self.silent_calls_percentage: Optional[float] = payload.get( + "silent_calls_percentage" + ) + self.calls_by_device_type: Optional[Dict[str, int]] = payload.get( + "calls_by_device_type" + ) + self.answer_rate_device_type: Optional[Dict[str, float]] = payload.get( + "answer_rate_device_type" + ) + self.blocked_calls_by_carrier: Optional[List[str]] = payload.get( + "blocked_calls_by_carrier" + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.answering_machine_detection: Optional[str] = payload.get( + "answering_machine_detection" + ) + self.report: Optional[str] = payload.get("report") + + self._solution = { + "report_id": report_id or self.report_id, + } + + self._context: Optional[ReportContext] = None + + @property + def _proxy(self) -> "ReportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReportContext for this ReportInstance + """ + if self._context is None: + self._context = ReportContext( + self._version, + report_id=self._solution["report_id"], + ) + return self._context + + def create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> "ReportInstance": + """ + Create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + return self._proxy.create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + async def create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> "ReportInstance": + """ + Asynchronous coroutine to create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + return await self._proxy.create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + def create_with_http_info( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ReportInstance with HTTP info + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + async def create_with_http_info_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ReportInstance with HTTP info + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request, + ) + + def fetch(self) -> "ReportInstance": + """ + Fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReportInstance": + """ + Asynchronous coroutine to fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReportContext(InstanceContext): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + def __init__(self, version: Version, report_id: str): + """ + Initialize the ReportContext + + :param version: Version that contains the resource + :param report_id: A unique request id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "report_id": report_id, + } + self._uri = "/Voice/Reports/{report_id}".format(**self._solution) + + def _create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_account_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ReportInstance: + """ + Create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + payload, _, _ = self._create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + return ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + def create_with_http_info( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ReportInstance and return response metadata + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + instance = ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_v2_create_account_report_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ReportInstance: + """ + Asynchronous coroutine to create the ReportInstance + + :param insights_v2_create_account_report_request: + + :returns: The created ReportInstance + """ + payload, _, _ = await self._create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + return ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + + async def create_with_http_info_async( + self, + insights_v2_create_account_report_request: Union[ + InsightsV2CreateAccountReportRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ReportInstance and return response metadata + + :param insights_v2_create_account_report_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_v2_create_account_report_request=insights_v2_create_account_report_request + ) + instance = ReportInstance( + self._version, payload, report_id=self._solution["report_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReportInstance: + """ + Fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + payload, _, _ = self._fetch() + return ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReportInstance: + """ + Asynchronous coroutine to fetch the ReportInstance + + + :returns: The fetched ReportInstance + """ + payload, _, _ = await self._fetch_async() + return ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReportInstance( + self._version, + payload, + report_id=self._solution["report_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ReportList(ListResource): + + class AccountReportAnsweringMachineDetection(object): + """ + :ivar total_calls: Total number of calls with answering machine detection enabled (AMD). + :ivar answered_by_human_percentage: Percentage of calls marked as answered by human. + :ivar answered_by_machine_percentage: Percentage of calls marked as answered by machined related like the following: `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax` + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_calls: Optional[int] = payload.get("total_calls") + self.answered_by_human_percentage: Optional[float] = payload.get( + "answered_by_human_percentage" + ) + self.answered_by_machine_percentage: Optional[float] = payload.get( + "answered_by_machine_percentage" + ) + + def to_dict(self): + return { + "total_calls": self.total_calls, + "answered_by_human_percentage": self.answered_by_human_percentage, + "answered_by_machine_percentage": self.answered_by_machine_percentage, + } + + class AccountReportCallDirection(object): + """ + :ivar outbound: Number of outbound calls + :ivar inbound: Number of inbound calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound: Optional[int] = payload.get("outbound") + self.inbound: Optional[int] = payload.get("inbound") + + def to_dict(self): + return { + "outbound": self.outbound, + "inbound": self.inbound, + } + + class AccountReportCallState(object): + """ + :ivar completed: Number of completed calls + :ivar fail: Number of failed calls + :ivar busy: Number of busy calls + :ivar noanswer: Number of no-answer calls + :ivar canceled: Number of canceled calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.completed: Optional[int] = payload.get("completed") + self.fail: Optional[int] = payload.get("fail") + self.busy: Optional[int] = payload.get("busy") + self.noanswer: Optional[int] = payload.get("noanswer") + self.canceled: Optional[int] = payload.get("canceled") + + def to_dict(self): + return { + "completed": self.completed, + "fail": self.fail, + "busy": self.busy, + "noanswer": self.noanswer, + "canceled": self.canceled, + } + + class AccountReportCallType(object): + """ + :ivar carrier: Number of carrier calls + :ivar sip: Number of SIP calls + :ivar trunking: Number of trunking calls + :ivar client: Number of client calls + :ivar whatsapp: Number of WhatsApp Business calls + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[int] = payload.get("carrier") + self.sip: Optional[int] = payload.get("sip") + self.trunking: Optional[int] = payload.get("trunking") + self.client: Optional[int] = payload.get("client") + self.whatsapp: Optional[int] = payload.get("whatsapp") + + def to_dict(self): + return { + "carrier": self.carrier, + "sip": self.sip, + "trunking": self.trunking, + "client": self.client, + "whatsapp": self.whatsapp, + } + + class AccountReportKYT(object): + """ + :ivar outbound_carrier_calling: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.outbound_carrier_calling: Optional[ + AccountReportKYTOutboundCarrierCalling + ] = payload.get("outbound_carrier_calling") + + def to_dict(self): + return { + "outbound_carrier_calling": ( + self.outbound_carrier_calling.to_dict() + if self.outbound_carrier_calling is not None + else None + ), + } + + class AccountReportKYTOutboundCarrierCalling(object): + """ + :ivar unique_calling_numbers: Number of unique PSTN calling numbers to non-Twilio numbers during the report period. + :ivar unique_called_numbers: Number of unique non-Twilio PSTN called numbers during the report period. + :ivar blocked_calls_by_carrier: Percentage of blocked calls by carrier per country. + :ivar short_duration_calls_percentage: Percentage of completed outbound calls under 10 seconds (PSTN Short call tags); More than 15% is typically low trust measured. + :ivar long_duration_calls_percentage: Percentage of long duration calls ( >= 60 seconds) + :ivar potential_robocalls_percentage: Percentage of completed outbound calls to unassigned or unallocated phone numbers. + :ivar branded_calling: + :ivar voice_integrity: + :ivar stir_shaken: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_calling_numbers: Optional[int] = payload.get( + "unique_calling_numbers" + ) + self.unique_called_numbers: Optional[int] = payload.get( + "unique_called_numbers" + ) + self.blocked_calls_by_carrier: Optional[List[CountyCarrierValue]] = ( + payload.get("blocked_calls_by_carrier") + ) + self.short_duration_calls_percentage: Optional[float] = payload.get( + "short_duration_calls_percentage" + ) + self.long_duration_calls_percentage: Optional[float] = payload.get( + "long_duration_calls_percentage" + ) + self.potential_robocalls_percentage: Optional[float] = payload.get( + "potential_robocalls_percentage" + ) + self.branded_calling: Optional[BrandedCalling] = payload.get( + "branded_calling" + ) + self.voice_integrity: Optional[VoiceIntegrity] = payload.get( + "voice_integrity" + ) + self.stir_shaken: Optional[StirShaken] = payload.get("stir_shaken") + + def to_dict(self): + return { + "unique_calling_numbers": self.unique_calling_numbers, + "unique_called_numbers": self.unique_called_numbers, + "blocked_calls_by_carrier": ( + [ + blocked_calls_by_carrier.to_dict() + for blocked_calls_by_carrier in self.blocked_calls_by_carrier + ] + if self.blocked_calls_by_carrier is not None + else None + ), + "short_duration_calls_percentage": self.short_duration_calls_percentage, + "long_duration_calls_percentage": self.long_duration_calls_percentage, + "potential_robocalls_percentage": self.potential_robocalls_percentage, + "branded_calling": ( + self.branded_calling.to_dict() + if self.branded_calling is not None + else None + ), + "voice_integrity": ( + self.voice_integrity.to_dict() + if self.voice_integrity is not None + else None + ), + "stir_shaken": ( + self.stir_shaken.to_dict() if self.stir_shaken is not None else None + ), + } + + class AccountReportNetworkIssues(object): + """ + :ivar sdk: + :ivar twilio_gateway: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sdk: Optional[AccountReportNetworkIssuesSdk] = payload.get("sdk") + self.twilio_gateway: Optional[AccountReportNetworkIssuesTwilioGateway] = ( + payload.get("twilio_gateway") + ) + + def to_dict(self): + return { + "sdk": self.sdk.to_dict() if self.sdk is not None else None, + "twilio_gateway": ( + self.twilio_gateway.to_dict() + if self.twilio_gateway is not None + else None + ), + } + + class AccountReportNetworkIssuesSdk(object): + """ + :ivar ice_failures_percentage: Percentage of ICE connection failure tag that ICE candidates have failed to find compatible connection. + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.ice_failures_percentage: Optional[float] = payload.get( + "ice_failures_percentage" + ) + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "ice_failures_percentage": self.ice_failures_percentage, + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class AccountReportNetworkIssuesTwilioGateway(object): + """ + :ivar high_latency_percentage: Percentage of calls with high latency. + :ivar high_packet_loss_percentage: Percentage of calls with high packet loss. + :ivar high_jitter_percentage: Percentage of calls with high jitter. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.high_latency_percentage: Optional[float] = payload.get( + "high_latency_percentage" + ) + self.high_packet_loss_percentage: Optional[float] = payload.get( + "high_packet_loss_percentage" + ) + self.high_jitter_percentage: Optional[float] = payload.get( + "high_jitter_percentage" + ) + + def to_dict(self): + return { + "high_latency_percentage": self.high_latency_percentage, + "high_packet_loss_percentage": self.high_packet_loss_percentage, + "high_jitter_percentage": self.high_jitter_percentage, + } + + class BrandedCalling(object): + """ + :ivar total_branded_calls: Total number of Branded bundled calls. + :ivar percent_branded_calls: Percentage of Branded bundled calls over total outbound calls. + :ivar answer_rate: Answer rate for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds. + :ivar by_use_case: Details of branded calls by use case. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_branded_calls: Optional[int] = payload.get("total_branded_calls") + self.percent_branded_calls: Optional[float] = payload.get( + "percent_branded_calls" + ) + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + self.by_use_case: Optional[List[BrandedUseCaseDetail]] = payload.get( + "by_use_case" + ) + + def to_dict(self): + return { + "total_branded_calls": self.total_branded_calls, + "percent_branded_calls": self.percent_branded_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + "by_use_case": ( + [by_use_case.to_dict() for by_use_case in self.by_use_case] + if self.by_use_case is not None + else None + ), + } + + class BrandedUseCaseDetail(object): + """ + :ivar use_case: The name of supported use case for Branded calls. + :ivar enabled_phonenumbers: The number of phone numbers enabled Branded calls. + :ivar total_calls: The number of total outbound calls for the use case. + :ivar answer_rate: Answer rate per each use case for Branded bundled calls. + :ivar human_answer_rate: Rate of Branded bundled calls that were answered by Human per each use case for Branded bundled calls. + :ivar engagement_rate: Engagement Rate for Branded bundled calls where its call length is longer than 60 seconds per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.use_case: Optional[str] = payload.get("use_case") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + self.engagement_rate: Optional[float] = payload.get("engagement_rate") + + def to_dict(self): + return { + "use_case": self.use_case, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + "engagement_rate": self.engagement_rate, + } + + class CountyCarrierValueCarriers(object): + """ + :ivar carrier: The name of the carrier. + :ivar total_calls: Total number of outbound calls for the carrier in the country. + :ivar blocked_calls: Total number of blocked outbound calls for the carrier in the country. + :ivar blocked_calls_percentage: Percentage of blocked outbound calls for the carrier in the country. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.carrier: Optional[str] = payload.get("carrier") + self.total_calls: Optional[int] = payload.get("total_calls") + self.blocked_calls: Optional[int] = payload.get("blocked_calls") + self.blocked_calls_percentage: Optional[float] = payload.get( + "blocked_calls_percentage" + ) + + def to_dict(self): + return { + "carrier": self.carrier, + "total_calls": self.total_calls, + "blocked_calls": self.blocked_calls, + "blocked_calls_percentage": self.blocked_calls_percentage, + } + + class InsightsV2CreateAccountReportRequest(object): + """ + :ivar time_range: + :ivar filters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.time_range: Optional[ + ReportList.InsightsV2CreateAccountReportRequestTimeRange + ] = payload.get("time_range") + self.filters: Optional[List[ReportList.ReportFilter]] = payload.get( + "filters" + ) + + def to_dict(self): + return { + "time_range": ( + self.time_range.to_dict() if self.time_range is not None else None + ), + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + } + + class InsightsV2CreateAccountReportRequestTimeRange(object): + """ + :ivar start_datetime: Start date time of the report + :ivar end_datetime: End date time of the report + """ + + def __init__(self, payload: Dict[str, Any]): + + self.start_datetime: Optional[datetime] = payload.get("start_datetime") + self.end_datetime: Optional[datetime] = payload.get("end_datetime") + + def to_dict(self): + return { + "start_datetime": self.start_datetime, + "end_datetime": self.end_datetime, + } + + class ReportFilter(object): + """ + :ivar key: The name of the filter 'call_state', 'call_direction', 'call_type', 'twilio_regions', 'caller_country_code', 'callee_country_code', 'silent' + :ivar values: List of supported filter values for the field name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "key": self.key, + "values": self.values, + } + + class StirShaken(object): + """ + :ivar call_count: + :ivar percentage: + :ivar answer_rate: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.call_count: Optional[StirShakenCallCount] = payload.get("call_count") + self.percentage: Optional[StirShakenPercentage] = payload.get("percentage") + self.answer_rate: Optional[StirShakenAnswerRate] = payload.get( + "answer_rate" + ) + + def to_dict(self): + return { + "call_count": ( + self.call_count.to_dict() if self.call_count is not None else None + ), + "percentage": ( + self.percentage.to_dict() if self.percentage is not None else None + ), + "answer_rate": ( + self.answer_rate.to_dict() if self.answer_rate is not None else None + ), + } + + class StirShakenAnswerRate(object): + """ + :ivar stsh_a: Answer rate for Stir Shaken category A. + :ivar stsh_b: Answer rate for Stir Shaken category B. + :ivar stsh_c: Answer rate for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenCallCount(object): + """ + :ivar stsh_a: Total number of calls for Stir Shaken category A. + :ivar stsh_b: Total number of calls for Stir Shaken category B. + :ivar stsh_c: Total number of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[int] = payload.get("stsh_a") + self.stsh_b: Optional[int] = payload.get("stsh_b") + self.stsh_c: Optional[int] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class StirShakenPercentage(object): + """ + :ivar stsh_a: Percentage of calls for Stir Shaken category A. + :ivar stsh_b: Percentage of calls for Stir Shaken category B. + :ivar stsh_c: Percentage of calls for Stir Shaken category C. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.stsh_a: Optional[float] = payload.get("stsh_a") + self.stsh_b: Optional[float] = payload.get("stsh_b") + self.stsh_c: Optional[float] = payload.get("stsh_c") + + def to_dict(self): + return { + "stsh_a": self.stsh_a, + "stsh_b": self.stsh_b, + "stsh_c": self.stsh_c, + } + + class VoiceIntegrity(object): + """ + :ivar enabled_calls: Total number of calls with Voice Integrity enabled. + :ivar enabled_percentage: Percentage of calls with Voice Integrity enabled. + :ivar calls_per_bundle: Number of calls per Voice Integrity enabled Bundle Sid. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled_calls: Optional[int] = payload.get("enabled_calls") + self.enabled_percentage: Optional[float] = payload.get("enabled_percentage") + self.calls_per_bundle: Optional[List[VoiceIntegrityCallsPerBundle]] = ( + payload.get("calls_per_bundle") + ) + + def to_dict(self): + return { + "enabled_calls": self.enabled_calls, + "enabled_percentage": self.enabled_percentage, + "calls_per_bundle": ( + [ + calls_per_bundle.to_dict() + for calls_per_bundle in self.calls_per_bundle + ] + if self.calls_per_bundle is not None + else None + ), + } + + class VoiceIntegrityCallsPerBundle(object): + """ + :ivar bundle_sid: Voice Integrity Approved Profile Sid. + :ivar enabled_phonenumbers: The number of Voice Integrity enabled and registered phone numbers per Bundle Sid. + :ivar total_calls: The number of outbound calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar answer_rate: Answer rate for calls on Voice Integrity enabled and registered number per Bundle Sid. + :ivar human_answer_rate: Rate for calls on Voice Integrity enabled and registered number per Bundle Sid that were answered by Human per each use case for Branded bundled calls. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.enabled_phonenumbers: Optional[int] = payload.get( + "enabled_phonenumbers" + ) + self.total_calls: Optional[int] = payload.get("total_calls") + self.answer_rate: Optional[float] = payload.get("answer_rate") + self.human_answer_rate: Optional[float] = payload.get("human_answer_rate") + + def to_dict(self): + return { + "bundle_sid": self.bundle_sid, + "enabled_phonenumbers": self.enabled_phonenumbers, + "total_calls": self.total_calls, + "answer_rate": self.answer_rate, + "human_answer_rate": self.human_answer_rate, + } + + def __init__(self, version: Version): + """ + Initialize the ReportList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, report_id: str) -> ReportContext: + """ + Constructs a ReportContext + + :param report_id: A unique request id. + """ + return ReportContext(self._version, report_id=report_id) + + def __call__(self, report_id: str) -> ReportContext: + """ + Constructs a ReportContext + + :param report_id: A unique request id. + """ + return ReportContext(self._version, report_id=report_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/__init__.py b/twilio/rest/insights/v3/__init__.py new file mode 100644 index 0000000000..2939808165 --- /dev/null +++ b/twilio/rest/insights/v3/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.insights.v3.metadata import MetadataList +from twilio.rest.insights.v3.query import QueryList +from twilio.rest.insights.v3.query_job import QueryJobList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v3") + self._metadata: Optional[MetadataList] = None + self._query: Optional[QueryList] = None + self._query_jobs: Optional[QueryJobList] = None + + @property + def metadata(self) -> MetadataList: + if self._metadata is None: + self._metadata = MetadataList(self) + return self._metadata + + @property + def query(self) -> QueryList: + if self._query is None: + self._query = QueryList(self) + return self._query + + @property + def query_jobs(self) -> QueryJobList: + if self._query_jobs is None: + self._query_jobs = QueryJobList(self) + return self._query_jobs + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/metadata.py b/twilio/rest/insights/v3/metadata.py new file mode 100644 index 0000000000..30e8d8f110 --- /dev/null +++ b/twilio/rest/insights/v3/metadata.py @@ -0,0 +1,139 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MetadataInstance(InstanceResource): + """ + :ivar domain: The business domain name for which metadata is being provided + :ivar cubes: List of data cubes available in the domain, each containing measures and dimensions + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.domain: Optional[str] = payload.get("domain") + self.cubes: Optional[List[str]] = payload.get("cubes") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class MetadataList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MetadataList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InsightsDomains/Conversations/Metadata" + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MetadataInstance: + """ + Fetch the MetadataInstance + + + :returns: The fetched MetadataInstance + """ + payload, _, _ = self._fetch() + return MetadataInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MetadataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MetadataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> MetadataInstance: + """ + Asynchronously fetch the MetadataInstance + + + :returns: The fetched MetadataInstance + """ + payload, _, _ = await self._fetch_async() + return MetadataInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the MetadataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MetadataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/query.py b/twilio/rest/insights/v3/query.py new file mode 100644 index 0000000000..b65b0aaec0 --- /dev/null +++ b/twilio/rest/insights/v3/query.py @@ -0,0 +1,397 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class QueryInstance(InstanceResource): + """ + :ivar domain: Indicates the business domain the query was executed against + :ivar items: Array of result objects containing the query results. Each object contains properties matching the requested measures and dimensions. + :ivar meta: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.domain: Optional[str] = payload.get("domain") + self.items: Optional[List[Dict[str, object]]] = payload.get("items") + self.meta: Optional[str] = payload.get("meta") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class QueryList(ListResource): + + class InsightsQueryRequest(object): + """ + :ivar domain: The business domain to execute the query against + :ivar query: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.domain: Optional[str] = payload.get("domain") + self.query: Optional[QueryList.QueryDefinition] = payload.get("query") + + def to_dict(self): + return { + "domain": self.domain, + "query": self.query.to_dict() if self.query is not None else None, + } + + class QueryDefinition(object): + """ + :ivar measures: Array of measures to retrieve, representing quantitative values or metrics to be calculated + :ivar dimensions: Array of dimensions to retrieve, representing categorical attributes for grouping and organizing data + :ivar filters: Nested filter conditions. Always use `op` and `expressions`. + :ivar order_by: Specifications for sorting the query results by specific fields in ascending or descending order + """ + + def __init__(self, payload: Dict[str, Any]): + + self.measures: Optional[List[str]] = payload.get("measures") + self.dimensions: Optional[List[str]] = payload.get("dimensions") + self.filters: Optional[List[QueryList.QueryDefinitionFilters]] = ( + payload.get("filters") + ) + self.order_by: Optional[List[QueryList.QueryDefinitionOrderBy]] = ( + payload.get("orderBy") + ) + + def to_dict(self): + return { + "measures": self.measures, + "dimensions": self.dimensions, + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "orderBy": ( + [order_by.to_dict() for order_by in self.order_by] + if self.order_by is not None + else None + ), + } + + class QueryDefinitionFilters(object): + """ + :ivar op: + :ivar expressions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.expressions: Optional[ + List[QueryList.QueryDefinitionFiltersExpressions] + ] = payload.get("expressions") + + def to_dict(self): + return { + "op": self.op, + "expressions": ( + [expressions.to_dict() for expressions in self.expressions] + if self.expressions is not None + else None + ), + } + + class QueryDefinitionFiltersExpressions(object): + """ + :ivar op: + :ivar field: + :ivar values: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.field: Optional[str] = payload.get("field") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "op": self.op, + "field": self.field, + "values": self.values, + } + + class QueryDefinitionOrderBy(object): + """ + :ivar field: Dimension or measure to order by + :ivar direction: Sort order direction, ascending or descending + """ + + def __init__(self, payload: Dict[str, Any]): + + self.field: Optional[str] = payload.get("field") + self.direction: Optional["QueryInstance.str"] = payload.get("direction") + + def to_dict(self): + return { + "field": self.field, + "direction": self.direction, + } + + def __init__(self, version: Version): + """ + Initialize the QueryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InsightsDomains/Conversations/Query" + + def _create( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + } + ) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + def create( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> QueryInstance: + """ + Create the QueryInstance + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: The created QueryInstance + """ + payload, _, _ = self._create( + insights_query_request=insights_query_request, page_size=page_size + ) + return QueryInstance(self._version, payload) + + def create_with_http_info( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the QueryInstance and return response metadata + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_query_request=insights_query_request, page_size=page_size + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + } + ) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + async def create_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> QueryInstance: + """ + Asynchronously create the QueryInstance + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: The created QueryInstance + """ + payload, _, _ = await self._create_async( + insights_query_request=insights_query_request, page_size=page_size + ) + return QueryInstance(self._version, payload) + + async def create_with_http_info_async( + self, + insights_query_request: InsightsQueryRequest, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the QueryInstance and return response metadata + + :param insights_query_request: + :param page_size: Number of items per page + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_query_request=insights_query_request, page_size=page_size + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self, page_token: str) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageToken": page_token, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch(self, page_token: str) -> QueryInstance: + """ + Fetch the QueryInstance + + :param page_token: Pagination token + :returns: The fetched QueryInstance + """ + payload, _, _ = self._fetch(page_token=page_token) + return QueryInstance(self._version, payload) + + def fetch_with_http_info(self, page_token: str) -> ApiResponse: + """ + Fetch the QueryInstance and return response metadata + + :param page_token: Pagination token + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(page_token=page_token) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, page_token: str) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageToken": page_token, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async(self, page_token: str) -> QueryInstance: + """ + Asynchronously fetch the QueryInstance + + :param page_token: Pagination token + :returns: The fetched QueryInstance + """ + payload, _, _ = await self._fetch_async(page_token=page_token) + return QueryInstance(self._version, payload) + + async def fetch_with_http_info_async(self, page_token: str) -> ApiResponse: + """ + Asynchronously fetch the QueryInstance and return response metadata + + :param page_token: Pagination token + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(page_token=page_token) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/query_job.py b/twilio/rest/insights/v3/query_job.py new file mode 100644 index 0000000000..893dce9760 --- /dev/null +++ b/twilio/rest/insights/v3/query_job.py @@ -0,0 +1,1004 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class QueryJobInstance(InstanceResource): + + class LongRunningOperationStatus(object): + PENDING = "PENDING" + RUNNING = "RUNNING" + CANCELLED = "CANCELLED" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + """ + :ivar operation_id: + :ivar status: + :ivar status_url: + :ivar created_at: + :ivar completed_at: When the operation reached a terminal state. + :ivar error: Error details. Present only when status is FAILED. + :ivar result_url: URL to retrieve query results. Present only when status is COMPLETED. Supports pagination via pageSize and pageToken query parameters. + :ivar result_retention_period: ISO 8601 duration for how long results are retained. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + operation_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["QueryJobInstance.LongRunningOperationStatus"] = ( + payload.get("status") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.error: Optional[OperationError] = payload.get("error") + self.result_url: Optional[str] = payload.get("resultUrl") + self.result_retention_period: Optional[str] = payload.get( + "resultRetentionPeriod" + ) + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + self._context: Optional[QueryJobContext] = None + + @property + def _proxy(self) -> "QueryJobContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: QueryJobContext for this QueryJobInstance + """ + if self._context is None: + self._context = QueryJobContext( + self._version, + operation_id=self._solution["operation_id"], + ) + return self._context + + def fetch(self) -> "QueryJobInstance": + """ + Fetch the QueryJobInstance + + + :returns: The fetched QueryJobInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "QueryJobInstance": + """ + Asynchronous coroutine to fetch the QueryJobInstance + + + :returns: The fetched QueryJobInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueryJobInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueryJobInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class QueryJobContext(InstanceContext): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the QueryJobContext + + :param version: Version that contains the resource + :param operation_id: The unique identifier for the async query operation (TTID format). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = "/InsightsDomains/Conversations/QueryJobs/{operation_id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> QueryJobInstance: + """ + Fetch the QueryJobInstance + + + :returns: The fetched QueryJobInstance + """ + payload, _, _ = self._fetch() + return QueryJobInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueryJobInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = QueryJobInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> QueryJobInstance: + """ + Asynchronous coroutine to fetch the QueryJobInstance + + + :returns: The fetched QueryJobInstance + """ + payload, _, _ = await self._fetch_async() + return QueryJobInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueryJobInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = QueryJobInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class QueryJobPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> QueryJobInstance: + """ + Build an instance of QueryJobInstance + + :param payload: Payload response from the API + """ + + return QueryJobInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class QueryJobList(ListResource): + + class InsightsQueryRequest(object): + """ + :ivar domain: The business domain to execute the query against + :ivar query: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.domain: Optional[str] = payload.get("domain") + self.query: Optional[QueryList.QueryDefinition] = payload.get("query") + + def to_dict(self): + return { + "domain": self.domain, + "query": self.query.to_dict() if self.query is not None else None, + } + + class OperationError(object): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP status code that would have been returned for a synchronous failure + :ivar detail: Additional context about the failure + """ + + def __init__(self, payload: Dict[str, Any]): + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.detail: Optional[str] = payload.get("detail") + + def to_dict(self): + return { + "code": self.code, + "message": self.message, + "httpStatusCode": self.http_status_code, + "detail": self.detail, + } + + class QueryDefinition(object): + """ + :ivar measures: Array of measures to retrieve, representing quantitative values or metrics to be calculated + :ivar dimensions: Array of dimensions to retrieve, representing categorical attributes for grouping and organizing data + :ivar filters: Nested filter conditions. Always use `op` and `expressions`. + :ivar order_by: Specifications for sorting the query results by specific fields in ascending or descending order + """ + + def __init__(self, payload: Dict[str, Any]): + + self.measures: Optional[List[str]] = payload.get("measures") + self.dimensions: Optional[List[str]] = payload.get("dimensions") + self.filters: Optional[List[QueryList.QueryDefinitionFilters]] = ( + payload.get("filters") + ) + self.order_by: Optional[List[QueryList.QueryDefinitionOrderBy]] = ( + payload.get("orderBy") + ) + + def to_dict(self): + return { + "measures": self.measures, + "dimensions": self.dimensions, + "filters": ( + [filters.to_dict() for filters in self.filters] + if self.filters is not None + else None + ), + "orderBy": ( + [order_by.to_dict() for order_by in self.order_by] + if self.order_by is not None + else None + ), + } + + class QueryDefinitionFilters(object): + """ + :ivar op: + :ivar expressions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.expressions: Optional[ + List[QueryList.QueryDefinitionFiltersExpressions] + ] = payload.get("expressions") + + def to_dict(self): + return { + "op": self.op, + "expressions": ( + [expressions.to_dict() for expressions in self.expressions] + if self.expressions is not None + else None + ), + } + + class QueryDefinitionFiltersExpressions(object): + """ + :ivar op: + :ivar field: + :ivar values: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional["QueryInstance.str"] = payload.get("op") + self.field: Optional[str] = payload.get("field") + self.values: Optional[List[str]] = payload.get("values") + + def to_dict(self): + return { + "op": self.op, + "field": self.field, + "values": self.values, + } + + class QueryDefinitionOrderBy(object): + """ + :ivar field: Dimension or measure to order by + :ivar direction: Sort order direction, ascending or descending + """ + + def __init__(self, payload: Dict[str, Any]): + + self.field: Optional[str] = payload.get("field") + self.direction: Optional["QueryInstance.str"] = payload.get("direction") + + def to_dict(self): + return { + "field": self.field, + "direction": self.direction, + } + + def __init__(self, version: Version): + """ + Initialize the QueryJobList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InsightsDomains/Conversations/QueryJobs" + + def _create( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> QueryJobInstance: + """ + Create the QueryJobInstance + + :param insights_query_request: + :param idempotency_key: Client-generated UUIDv7 key to ensure idempotent behavior. Submitting the same key for identical requests returns the same operation without re-execution. Scoped to Account + Region. Retained for 24 hours. + + :returns: The created QueryJobInstance + """ + payload, _, _ = self._create( + insights_query_request=insights_query_request, + idempotency_key=idempotency_key, + ) + return QueryJobInstance(self._version, payload) + + def create_with_http_info( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the QueryJobInstance and return response metadata + + :param insights_query_request: + :param idempotency_key: Client-generated UUIDv7 key to ensure idempotent behavior. Submitting the same key for identical requests returns the same operation without re-execution. Scoped to Account + Region. Retained for 24 hours. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + insights_query_request=insights_query_request, + idempotency_key=idempotency_key, + ) + instance = QueryJobInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = insights_query_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> QueryJobInstance: + """ + Asynchronously create the QueryJobInstance + + :param insights_query_request: + :param idempotency_key: Client-generated UUIDv7 key to ensure idempotent behavior. Submitting the same key for identical requests returns the same operation without re-execution. Scoped to Account + Region. Retained for 24 hours. + + :returns: The created QueryJobInstance + """ + payload, _, _ = await self._create_async( + insights_query_request=insights_query_request, + idempotency_key=idempotency_key, + ) + return QueryJobInstance(self._version, payload) + + async def create_with_http_info_async( + self, + insights_query_request: InsightsQueryRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the QueryJobInstance and return response metadata + + :param insights_query_request: + :param idempotency_key: Client-generated UUIDv7 key to ensure idempotent behavior. Submitting the same key for identical requests returns the same operation without re-execution. Scoped to Account + Region. Retained for 24 hours. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + insights_query_request=insights_query_request, + idempotency_key=idempotency_key, + ) + instance = QueryJobInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[QueryJobInstance]: + """ + Streams QueryJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[QueryJobInstance]: + """ + Asynchronously streams QueryJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams QueryJobInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams QueryJobInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueryJobInstance]: + """ + Lists QueryJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueryJobInstance]: + """ + Asynchronously lists QueryJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists QueryJobInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists QueryJobInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param LongRunningOperationStatus status: Filter by operation status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + ) -> QueryJobPage: + """ + Retrieve a single page of QueryJobInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param status: Filter by operation status. + :returns: Page of QueryJobInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "status": status, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueryJobPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + status: Union[LongRunningOperationStatus, object] = values.unset, + ) -> QueryJobPage: + """ + Asynchronously retrieve a single page of QueryJobInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param status: Filter by operation status. + :returns: Page of QueryJobInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "status": status, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueryJobPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + status: Union[LongRunningOperationStatus, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param status: Filter by operation status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueryJobPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = QueryJobPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[LongRunningOperationStatus, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param status: Filter by operation status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with QueryJobPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = QueryJobPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> QueryJobPage: + """ + Retrieve a specific page of QueryJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueryJobInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return QueryJobPage(self._version, response) + + async def get_page_async(self, target_url: str) -> QueryJobPage: + """ + Asynchronously retrieve a specific page of QueryJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueryJobInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return QueryJobPage(self._version, response) + + def get(self, operation_id: str) -> QueryJobContext: + """ + Constructs a QueryJobContext + + :param operation_id: The unique identifier for the async query operation (TTID format). + """ + return QueryJobContext(self._version, operation_id=operation_id) + + def __call__(self, operation_id: str) -> QueryJobContext: + """ + Constructs a QueryJobContext + + :param operation_id: The unique identifier for the async query operation (TTID format). + """ + return QueryJobContext(self._version, operation_id=operation_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/insights/v3/result.py b/twilio/rest/insights/v3/result.py new file mode 100644 index 0000000000..239c7208dc --- /dev/null +++ b/twilio/rest/insights/v3/result.py @@ -0,0 +1,208 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 API. Includes synchronous Query, Metadata, and Async Query (long-running operation) endpoints. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ResultInstance(InstanceResource): + """ + :ivar domain: Indicates the business domain the query was executed against + :ivar items: Array of result objects containing the query results. Each object contains properties matching the requested measures and dimensions. + :ivar meta: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], operation_id: str): + super().__init__(version) + + self.domain: Optional[str] = payload.get("domain") + self.items: Optional[List[Dict[str, object]]] = payload.get("items") + self.meta: Optional[str] = payload.get("meta") + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ResultList(ListResource): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the ResultList + + :param version: Version that contains the resource + :param operation_id: The unique identifier for the async query operation. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = ( + "/InsightsDomains/Conversations/QueryJobs/{operation_id}/Results".format( + **self._solution + ) + ) + + def _fetch( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ResultInstance: + """ + Fetch the ResultInstance + + :param page_size: The maximum number of resources to return:param page_token: Token for pagination + :returns: The fetched ResultInstance + """ + payload, _, _ = self._fetch(page_size=page_size, page_token=page_token) + return ResultInstance( + self._version, payload, operation_id=self._solution["operation_id"] + ) + + def fetch_with_http_info( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the ResultInstance and return response metadata + + :param page_size: The maximum number of resources to return:param page_token: Token for pagination + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + page_size=page_size, page_token=page_token + ) + instance = ResultInstance( + self._version, payload, operation_id=self._solution["operation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ResultInstance: + """ + Asynchronously fetch the ResultInstance + + :param page_size: The maximum number of resources to return:param page_token: Token for pagination + :returns: The fetched ResultInstance + """ + payload, _, _ = await self._fetch_async( + page_size=page_size, page_token=page_token + ) + return ResultInstance( + self._version, payload, operation_id=self._solution["operation_id"] + ) + + async def fetch_with_http_info_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously fetch the ResultInstance and return response metadata + + :param page_size: The maximum number of resources to return:param page_token: Token for pagination + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + page_size=page_size, page_token=page_token + ) + instance = ResultInstance( + self._version, payload, operation_id=self._solution["operation_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/IntelligenceBase.py b/twilio/rest/intelligence/IntelligenceBase.py index 0546bc15ae..937e497fe9 100644 --- a/twilio/rest/intelligence/IntelligenceBase.py +++ b/twilio/rest/intelligence/IntelligenceBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.intelligence.v2 import V2 +from twilio.rest.intelligence.v3 import V3 class IntelligenceBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://intelligence.twilio.com") self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v2(self) -> V2: @@ -36,6 +38,15 @@ def v2(self) -> V2: self._v2 = V2(self) return self._v2 + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Intelligence + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/intelligence/v2/custom_operator.py b/twilio/rest/intelligence/v2/custom_operator.py index 3dd73d47bb..899e6e0c6a 100644 --- a/twilio/rest/intelligence/v2/custom_operator.py +++ b/twilio/rest/intelligence/v2/custom_operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,8 @@ class Availability(object): BETA = "beta" PUBLIC = "public" RETIRED = "retired" + GENERAL_AVAILABILITY = "general-availability" + DEPRECATED = "deprecated" """ :ivar account_sid: The unique SID identifier of the Account the Custom Operator belongs to. @@ -72,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CustomOperatorContext] = None @property @@ -107,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomOperatorInstance": """ Fetch the CustomOperatorInstance @@ -125,6 +147,24 @@ async def fetch_async(self) -> "CustomOperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: str, @@ -167,6 +207,48 @@ async def update_async( if_match=if_match, ) + def update_with_http_info( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomOperatorInstance with HTTP info + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance with HTTP info + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,6 +276,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Operators/Custom/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomOperatorInstance @@ -201,10 +297,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -213,69 +331,120 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CustomOperatorInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CustomOperatorInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CustomOperatorInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CustomOperatorInstance: + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + payload, _, _ = self._fetch() return CustomOperatorInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CustomOperatorInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CustomOperatorInstance + Fetch the CustomOperatorInstance and return response metadata - :returns: The fetched CustomOperatorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CustomOperatorInstance: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + payload, _, _ = await self._fetch_async() return CustomOperatorInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: str, config: object, if_match: Union[str, object] = values.unset, - ) -> CustomOperatorInstance: + ) -> tuple: """ - Update the CustomOperatorInstance - - :param friendly_name: A human-readable name of this resource, up to 64 characters. - :param config: Operator configuration, following the schema defined by the Operator Type. - :param if_match: The If-Match HTTP request header + Internal helper for update operation - :returns: The updated CustomOperatorInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,20 +464,18 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: str, config: object, if_match: Union[str, object] = values.unset, ) -> CustomOperatorInstance: """ - Asynchronous coroutine to update the CustomOperatorInstance + Update the CustomOperatorInstance :param friendly_name: A human-readable name of this resource, up to 64 characters. :param config: Operator configuration, following the schema defined by the Operator Type. @@ -316,6 +483,46 @@ async def update_async( :returns: The updated CustomOperatorInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, config=config, if_match=if_match + ) + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomOperatorInstance and return response metadata + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, config=config, if_match=if_match + ) + instance = CustomOperatorInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -334,12 +541,53 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> CustomOperatorInstance: + """ + Asynchronous coroutine to update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, config=config, if_match=if_match + ) return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance and return response metadata + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, config=config, if_match=if_match + ) + instance = CustomOperatorInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -358,6 +606,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CustomOperatorInstance: :param payload: Payload response from the API """ + return CustomOperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -382,17 +631,12 @@ def __init__(self, version: Version): self._uri = "/Operators/Custom" - def create( - self, friendly_name: str, operator_type: str, config: object - ) -> CustomOperatorInstance: + def _create(self, friendly_name: str, operator_type: str, config: object) -> tuple: """ - Create the CustomOperatorInstance - - :param friendly_name: A human readable description of the new Operator, up to 64 characters. - :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. - :param config: Operator configuration, following the schema defined by the Operator Type. + Internal helper for create operation - :returns: The created CustomOperatorInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,17 +652,15 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CustomOperatorInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, operator_type: str, config: object ) -> CustomOperatorInstance: """ - Asynchronously create the CustomOperatorInstance + Create the CustomOperatorInstance :param friendly_name: A human readable description of the new Operator, up to 64 characters. :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. @@ -426,6 +668,38 @@ async def create_async( :returns: The created CustomOperatorInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + return CustomOperatorInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, operator_type: str, config: object + ) -> ApiResponse: + """ + Create the CustomOperatorInstance and return response metadata + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + instance = CustomOperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -440,12 +714,45 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> CustomOperatorInstance: + """ + Asynchronously create the CustomOperatorInstance + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: The created CustomOperatorInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) return CustomOperatorInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: str, operator_type: str, config: object + ) -> ApiResponse: + """ + Asynchronously create the CustomOperatorInstance and return response metadata + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + instance = CustomOperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, availability: Union[ @@ -516,6 +823,74 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union[ @@ -541,6 +916,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -575,6 +951,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -585,6 +962,72 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union[ @@ -667,6 +1110,92 @@ async def page_async( ) return CustomOperatorPage(self._version, response) + def page_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomOperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomOperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CustomOperatorPage: """ Retrieve a specific page of CustomOperatorInstance records from the API. diff --git a/twilio/rest/intelligence/v2/operator.py b/twilio/rest/intelligence/v2/operator.py index 984c46d724..10c2ea5d5b 100644 --- a/twilio/rest/intelligence/v2/operator.py +++ b/twilio/rest/intelligence/v2/operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,8 @@ class Availability(object): INTERNAL = "internal" BETA = "beta" PUBLIC = "public" + DEPRECATED = "deprecated" + GENERAL_AVAILABILITY = "general-availability" RETIRED = "retired" """ @@ -72,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[OperatorContext] = None @property @@ -107,6 +111,24 @@ async def fetch_async(self) -> "OperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,48 +156,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Operators/{sid}".format(**self._solution) - def fetch(self) -> OperatorInstance: + def _fetch(self) -> tuple: """ - Fetch the OperatorInstance - + Internal helper for fetch operation - :returns: The fetched OperatorInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + :returns: The fetched OperatorInstance + """ + payload, _, _ = self._fetch() return OperatorInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> OperatorInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the OperatorInstance + Fetch the OperatorInstance and return response metadata - :returns: The fetched OperatorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = await self._fetch_async() return OperatorInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorInstance: :param payload: Payload response from the API """ + return OperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -284,6 +355,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union["OperatorInstance.Availability", object] = values.unset, @@ -307,6 +442,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -339,6 +475,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -349,6 +486,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union["OperatorInstance.Availability", object] = values.unset, @@ -427,6 +626,88 @@ async def page_async( ) return OperatorPage(self._version, response) + def page_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> OperatorPage: """ Retrieve a specific page of OperatorInstance records from the API. diff --git a/twilio/rest/intelligence/v2/operator_attachment.py b/twilio/rest/intelligence/v2/operator_attachment.py index 6080bc5ebf..d05769e12e 100644 --- a/twilio/rest/intelligence/v2/operator_attachment.py +++ b/twilio/rest/intelligence/v2/operator_attachment.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( "service_sid": service_sid or self.service_sid, "operator_sid": operator_sid or self.operator_sid, } + self._context: Optional[OperatorAttachmentContext] = None @property @@ -80,6 +82,24 @@ async def create_async(self) -> "OperatorAttachmentInstance": """ return await self._proxy.create_async() + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + def delete(self) -> bool: """ Deletes the OperatorAttachmentInstance @@ -98,6 +118,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -129,6 +167,23 @@ def __init__(self, version: Version, service_sid: str, operator_sid: str): **self._solution ) + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create(self) -> OperatorAttachmentInstance: """ Create the OperatorAttachmentInstance @@ -136,16 +191,46 @@ def create(self) -> OperatorAttachmentInstance: :returns: The created OperatorAttachmentInstance """ - data = values.of({}) + payload, _, _ = self._create() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) - payload = self._version.create(method="POST", uri=self._uri, data=data) + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance and return response metadata - return OperatorAttachmentInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = OperatorAttachmentInstance( self._version, payload, service_sid=self._solution["service_sid"], operator_sid=self._solution["operator_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async(self) -> OperatorAttachmentInstance: """ @@ -154,18 +239,43 @@ async def create_async(self) -> OperatorAttachmentInstance: :returns: The created OperatorAttachmentInstance """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + payload, _, _ = await self._create_async() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], ) - return OperatorAttachmentInstance( + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = OperatorAttachmentInstance( self._version, payload, service_sid=self._solution["service_sid"], operator_sid=self._solution["operator_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -174,10 +284,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -186,12 +318,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/intelligence/v2/operator_attachments.py b/twilio/rest/intelligence/v2/operator_attachments.py index 19a875f76b..0bfbacdcf7 100644 --- a/twilio/rest/intelligence/v2/operator_attachments.py +++ b/twilio/rest/intelligence/v2/operator_attachments.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__( self._solution = { "service_sid": service_sid or self.service_sid, } + self._context: Optional[OperatorAttachmentsContext] = None @property @@ -77,6 +79,24 @@ async def fetch_async(self) -> "OperatorAttachmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -104,48 +124,96 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Operators".format(**self._solution) - def fetch(self) -> OperatorAttachmentsInstance: + def _fetch(self) -> tuple: """ - Fetch the OperatorAttachmentsInstance + Internal helper for fetch operation - - :returns: The fetched OperatorAttachmentsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> OperatorAttachmentsInstance: + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + payload, _, _ = self._fetch() return OperatorAttachmentsInstance( self._version, payload, service_sid=self._solution["service_sid"], ) - async def fetch_async(self) -> OperatorAttachmentsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the OperatorAttachmentsInstance + Fetch the OperatorAttachmentsInstance and return response metadata - :returns: The fetched OperatorAttachmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> OperatorAttachmentsInstance: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + payload, _, _ = await self._fetch_async() return OperatorAttachmentsInstance( self._version, payload, service_sid=self._solution["service_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/intelligence/v2/operator_type.py b/twilio/rest/intelligence/v2/operator_type.py index b14e677ad2..288595ad02 100644 --- a/twilio/rest/intelligence/v2/operator_type.py +++ b/twilio/rest/intelligence/v2/operator_type.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -36,6 +37,7 @@ class OutputType(object): TEXT_EXTRACTION = "text-extraction" TEXT_EXTRACTION_NORMALIZED = "text-extraction-normalized" TEXT_GENERATION = "text-generation" + JSON = "json" class Provider(object): TWILIO = "twilio" @@ -94,6 +96,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[OperatorTypeContext] = None @property @@ -129,6 +132,24 @@ async def fetch_async(self) -> "OperatorTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,48 +177,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/OperatorTypes/{sid}".format(**self._solution) - def fetch(self) -> OperatorTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the OperatorTypeInstance - + Internal helper for fetch operation - :returns: The fetched OperatorTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> OperatorTypeInstance: + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + payload, _, _ = self._fetch() return OperatorTypeInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> OperatorTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the OperatorTypeInstance + Fetch the OperatorTypeInstance and return response metadata - :returns: The fetched OperatorTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> OperatorTypeInstance: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + payload, _, _ = await self._fetch_async() return OperatorTypeInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -216,6 +285,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorTypeInstance: :param payload: Payload response from the API """ + return OperatorTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -242,6 +312,7 @@ def __init__(self, version: Version): def stream( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[OperatorTypeInstance]: @@ -251,6 +322,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -261,12 +333,13 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) + page = self.page(language_code=language_code, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[OperatorTypeInstance]: @@ -276,6 +349,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -286,12 +360,71 @@ async def stream_async( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) + page = await self.page_async( + language_code=language_code, page_size=limits["page_size"] + ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[OperatorTypeInstance]: @@ -300,6 +433,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -309,8 +443,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + language_code=language_code, limit=limit, page_size=page_size, ) @@ -318,6 +454,7 @@ def list( async def list_async( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[OperatorTypeInstance]: @@ -326,6 +463,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -335,16 +473,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + language_code=language_code, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, + language_code: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -353,6 +550,7 @@ def page( Retrieve a single page of OperatorTypeInstance records from the API. Request is executed immediately + :param language_code: Returns Operator Types that support the provided language code. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -361,6 +559,7 @@ def page( """ data = values.of( { + "LanguageCode": language_code, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -378,6 +577,7 @@ def page( async def page_async( self, + language_code: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -386,6 +586,7 @@ async def page_async( Asynchronously retrieve a single page of OperatorTypeInstance records from the API. Request is executed immediately + :param language_code: Returns Operator Types that support the provided language code. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -394,6 +595,7 @@ async def page_async( """ data = values.of( { + "LanguageCode": language_code, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -409,6 +611,82 @@ async def page_async( ) return OperatorTypePage(self._version, response) + def page_with_http_info( + self, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param language_code: Returns Operator Types that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorTypePage, status code, and headers + """ + data = values.of( + { + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param language_code: Returns Operator Types that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorTypePage, status code, and headers + """ + data = values.of( + { + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> OperatorTypePage: """ Retrieve a specific page of OperatorTypeInstance records from the API. diff --git a/twilio/rest/intelligence/v2/prebuilt_operator.py b/twilio/rest/intelligence/v2/prebuilt_operator.py index 50693f29c2..8dc5cdac4e 100644 --- a/twilio/rest/intelligence/v2/prebuilt_operator.py +++ b/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,7 @@ class Availability(object): BETA = "beta" PUBLIC = "public" RETIRED = "retired" + GENERAL_AVAILABILITY = "general-availability" """ :ivar account_sid: The unique SID identifier of the Account the Pre-built Operator belongs to. @@ -72,6 +74,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PrebuiltOperatorContext] = None @property @@ -107,6 +110,24 @@ async def fetch_async(self) -> "PrebuiltOperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,48 +155,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Operators/PreBuilt/{sid}".format(**self._solution) - def fetch(self) -> PrebuiltOperatorInstance: + def _fetch(self) -> tuple: """ - Fetch the PrebuiltOperatorInstance - + Internal helper for fetch operation - :returns: The fetched PrebuiltOperatorInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PrebuiltOperatorInstance: + """ + Fetch the PrebuiltOperatorInstance + + :returns: The fetched PrebuiltOperatorInstance + """ + payload, _, _ = self._fetch() return PrebuiltOperatorInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> PrebuiltOperatorInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PrebuiltOperatorInstance + Fetch the PrebuiltOperatorInstance and return response metadata - :returns: The fetched PrebuiltOperatorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PrebuiltOperatorInstance: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + payload, _, _ = await self._fetch_async() return PrebuiltOperatorInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,6 +263,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PrebuiltOperatorInstance: :param payload: Payload response from the API """ + return PrebuiltOperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -288,6 +358,74 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union[ @@ -313,6 +451,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -347,6 +486,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -357,6 +497,72 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union[ @@ -439,6 +645,92 @@ async def page_async( ) return PrebuiltOperatorPage(self._version, response) + def page_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PrebuiltOperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PrebuiltOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PrebuiltOperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PrebuiltOperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PrebuiltOperatorPage: """ Retrieve a specific page of PrebuiltOperatorInstance records from the API. diff --git a/twilio/rest/intelligence/v2/service.py b/twilio/rest/intelligence/v2/service.py index fac3eb8473..6a16c052fe 100644 --- a/twilio/rest/intelligence/v2/service.py +++ b/twilio/rest/intelligence/v2/service.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,6 +47,7 @@ class HttpMethod(object): :ivar webhook_http_method: :ivar read_only_attached_operator_sids: Operator sids attached to this service, read only :ivar version: The version number of this Service. + :ivar encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. """ def __init__( @@ -77,10 +79,14 @@ def __init__( "read_only_attached_operator_sids" ) self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -116,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -134,6 +158,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -145,6 +187,7 @@ def update( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> "ServiceInstance": """ Update the ServiceInstance @@ -158,6 +201,7 @@ def update( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ @@ -171,6 +215,7 @@ def update( media_redaction=media_redaction, webhook_url=webhook_url, webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, ) async def update_async( @@ -184,6 +229,7 @@ async def update_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> "ServiceInstance": """ Asynchronous coroutine to update the ServiceInstance @@ -197,6 +243,7 @@ async def update_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ @@ -210,6 +257,91 @@ async def update_async( media_redaction=media_redaction, webhook_url=webhook_url, webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, ) def __repr__(self) -> str: @@ -239,6 +371,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Services/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -246,10 +392,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -258,56 +426,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, auto_transcribe: Union[bool, object] = values.unset, @@ -318,21 +540,13 @@ def update( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, - ) -> ServiceInstance: + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Update the ServiceInstance - - :param if_match: The If-Match HTTP request header - :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. - :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. - :param friendly_name: A human readable description of this resource, up to 64 characters. - :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. - :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. - :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. - :param webhook_url: The URL Twilio will request when executing the Webhook. - :param webhook_http_method: + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -345,6 +559,7 @@ def update( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({}) @@ -358,13 +573,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, if_match: Union[str, object] = values.unset, auto_transcribe: Union[bool, object] = values.unset, @@ -375,9 +588,10 @@ async def update_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param if_match: The If-Match HTTP request header :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. @@ -388,9 +602,87 @@ async def update_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -402,6 +694,7 @@ async def update_async( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({}) @@ -415,21 +708,106 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + async def update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - + Asynchronous coroutine to update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + class ServicePage(Page): @@ -439,6 +817,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -463,7 +842,7 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, unique_name: str, auto_transcribe: Union[bool, object] = values.unset, @@ -474,21 +853,13 @@ def create( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, - ) -> ServiceInstance: + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. - :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. - :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. - :param friendly_name: A human readable description of this resource, up to 64 characters. - :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. - :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. - :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. - :param webhook_url: The URL Twilio will request when executing the Webhook. - :param webhook_http_method: - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -502,6 +873,7 @@ def create( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -510,13 +882,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, auto_transcribe: Union[bool, object] = values.unset, @@ -527,9 +897,10 @@ async def create_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. @@ -540,9 +911,87 @@ async def create_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -555,6 +1004,7 @@ async def create_async( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -563,12 +1013,97 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -619,6 +1154,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -638,6 +1223,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -664,6 +1250,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -672,6 +1259,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -738,6 +1375,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/intelligence/v2/transcript/__init__.py b/twilio/rest/intelligence/v2/transcript/__init__.py index c2141bb5da..19284fa98d 100644 --- a/twilio/rest/intelligence/v2/transcript/__init__.py +++ b/twilio/rest/intelligence/v2/transcript/__init__.py @@ -15,11 +15,18 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version from twilio.base.page import Page +from twilio.rest.intelligence.v2.transcript.encrypted_operator_results import ( + EncryptedOperatorResultsList, +) +from twilio.rest.intelligence.v2.transcript.encrypted_sentences import ( + EncryptedSentencesList, +) from twilio.rest.intelligence.v2.transcript.media import MediaList from twilio.rest.intelligence.v2.transcript.operator_result import OperatorResultList from twilio.rest.intelligence.v2.transcript.sentence import SentenceList @@ -31,8 +38,10 @@ class Status(object): QUEUED = "queued" IN_PROGRESS = "in-progress" COMPLETED = "completed" + NEW = "new" FAILED = "failed" CANCELED = "canceled" + ERROR = "error" """ :ivar account_sid: The unique SID identifier of the Account. @@ -49,6 +58,7 @@ class Status(object): :ivar duration: The duration of this Transcript's source :ivar url: The URL of this resource. :ivar redaction: If the transcript has been redacted, a redacted alternative of the transcript will be available. + :ivar encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :ivar links: """ @@ -77,11 +87,15 @@ def __init__( self.duration: Optional[int] = deserialize.integer(payload.get("duration")) self.url: Optional[str] = payload.get("url") self.redaction: Optional[bool] = payload.get("redaction") + self.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) self.links: Optional[Dict[str, object]] = payload.get("links") self._solution = { "sid": sid or self.sid, } + self._context: Optional[TranscriptContext] = None @property @@ -117,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptInstance": """ Fetch the TranscriptInstance @@ -135,6 +167,38 @@ async def fetch_async(self) -> "TranscriptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def encrypted_operator_results(self) -> EncryptedOperatorResultsList: + """ + Access the encrypted_operator_results + """ + return self._proxy.encrypted_operator_results + + @property + def encrypted_sentences(self) -> EncryptedSentencesList: + """ + Access the encrypted_sentences + """ + return self._proxy.encrypted_sentences + @property def media(self) -> MediaList: """ @@ -183,10 +247,26 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Transcripts/{sid}".format(**self._solution) + self._encrypted_operator_results: Optional[EncryptedOperatorResultsList] = None + self._encrypted_sentences: Optional[EncryptedSentencesList] = None self._media: Optional[MediaList] = None self._operator_results: Optional[OperatorResultList] = None self._sentences: Optional[SentenceList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptInstance @@ -194,10 +274,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -206,55 +308,133 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TranscriptInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TranscriptInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TranscriptInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptInstance: + """ + Fetch the TranscriptInstance + + :returns: The fetched TranscriptInstance + """ + payload, _, _ = self._fetch() return TranscriptInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> TranscriptInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TranscriptInstance + Fetch the TranscriptInstance and return response metadata - :returns: The fetched TranscriptInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TranscriptInstance: + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + payload, _, _ = await self._fetch_async() return TranscriptInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def encrypted_operator_results(self) -> EncryptedOperatorResultsList: + """ + Access the encrypted_operator_results + """ + if self._encrypted_operator_results is None: + self._encrypted_operator_results = EncryptedOperatorResultsList( + self._version, + self._solution["sid"], + ) + return self._encrypted_operator_results + + @property + def encrypted_sentences(self) -> EncryptedSentencesList: + """ + Access the encrypted_sentences + """ + if self._encrypted_sentences is None: + self._encrypted_sentences = EncryptedSentencesList( + self._version, + self._solution["sid"], + ) + return self._encrypted_sentences + @property def media(self) -> MediaList: """ @@ -309,6 +489,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptInstance: :param payload: Payload response from the API """ + return TranscriptInstance(self._version, payload) def __repr__(self) -> str: @@ -333,22 +514,18 @@ def __init__(self, version: Version): self._uri = "/Transcripts" - def create( + def _create( self, service_sid: str, channel: object, customer_key: Union[str, object] = values.unset, media_start_time: Union[datetime, object] = values.unset, - ) -> TranscriptInstance: + ) -> tuple: """ - Create the TranscriptInstance + Internal helper for create operation - :param service_sid: The unique SID identifier of the Service. - :param channel: JSON object describing Media Channel including Source and Participants - :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. - :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. - - :returns: The created TranscriptInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -365,13 +542,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TranscriptInstance(self._version, payload) - - async def create_async( + def create( self, service_sid: str, channel: object, @@ -379,7 +554,7 @@ async def create_async( media_start_time: Union[datetime, object] = values.unset, ) -> TranscriptInstance: """ - Asynchronously create the TranscriptInstance + Create the TranscriptInstance :param service_sid: The unique SID identifier of the Service. :param channel: JSON object describing Media Channel including Source and Participants @@ -388,6 +563,53 @@ async def create_async( :returns: The created TranscriptInstance """ + payload, _, _ = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + return TranscriptInstance(self._version, payload) + + def create_with_http_info( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptInstance and return response metadata + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + instance = TranscriptInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -403,12 +625,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> TranscriptInstance: + """ + Asynchronously create the TranscriptInstance + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: The created TranscriptInstance + """ + payload, _, _ = await self._create_async( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) return TranscriptInstance(self._version, payload) + async def create_with_http_info_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptInstance and return response metadata + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + instance = TranscriptInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, service_sid: Union[str, object] = values.unset, @@ -511,6 +782,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, service_sid: Union[str, object] = values.unset, @@ -546,6 +917,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( service_sid=service_sid, @@ -596,6 +968,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -612,6 +985,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, service_sid: Union[str, object] = values.unset, @@ -726,6 +1197,124 @@ async def page_async( ) return TranscriptPage(self._version, response) + def page_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptPage, status code, and headers + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptPage, status code, and headers + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TranscriptPage: """ Retrieve a specific page of TranscriptInstance records from the API. diff --git a/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py new file mode 100644 index 0000000000..4262a2ce09 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py @@ -0,0 +1,313 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EncryptedOperatorResultsInstance(InstanceResource): + """ + :ivar locations: The locations of the encrypted operator results. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.locations: Optional[List[str]] = payload.get("locations") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedOperatorResultsContext] = None + + @property + def _proxy(self) -> "EncryptedOperatorResultsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedOperatorResultsContext for this EncryptedOperatorResultsInstance + """ + if self._context is None: + self._context = EncryptedOperatorResultsContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class EncryptedOperatorResultsContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsContext + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/OperatorResults/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class EncryptedOperatorResultsList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + + def get(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py new file mode 100644 index 0000000000..ed2406926e --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py @@ -0,0 +1,309 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EncryptedSentencesInstance(InstanceResource): + """ + :ivar location: The location of the encrypted sentences. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.location: Optional[str] = payload.get("location") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedSentencesContext] = None + + @property + def _proxy(self) -> "EncryptedSentencesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedSentencesContext for this EncryptedSentencesInstance + """ + if self._context is None: + self._context = EncryptedSentencesContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EncryptedSentencesContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesContext + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/Sentences/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EncryptedSentencesList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + + def get(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/media.py b/twilio/rest/intelligence/v2/transcript/media.py index 76bc448e9b..a4d08a488d 100644 --- a/twilio/rest/intelligence/v2/transcript/media.py +++ b/twilio/rest/intelligence/v2/transcript/media.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -41,6 +42,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[MediaContext] = None @property @@ -84,6 +86,34 @@ async def fetch_async( redacted=redacted, ) + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -111,16 +141,15 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Transcripts/{sid}/Media".format(**self._solution) - def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: """ - Fetch the MediaInstance + Internal helper for fetch operation - :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. - - :returns: The fetched MediaInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } @@ -130,28 +159,52 @@ def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + payload, _, _ = self._fetch(redacted=redacted) return MediaInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async( + def fetch_with_http_info( self, redacted: Union[bool, object] = values.unset - ) -> MediaInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the MediaInstance + Fetch the MediaInstance and return response metadata :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. - :returns: The fetched MediaInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } @@ -161,16 +214,45 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) return MediaInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/intelligence/v2/transcript/operator_result.py b/twilio/rest/intelligence/v2/transcript/operator_result.py index 4b607b39e8..01af814a79 100644 --- a/twilio/rest/intelligence/v2/transcript/operator_result.py +++ b/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,11 +25,13 @@ class OperatorResultInstance(InstanceResource): class OperatorType(object): - CONVERSATION_CLASSIFY = "conversation_classify" - UTTERANCE_CLASSIFY = "utterance_classify" + CONVERSATION_CLASSIFY = "conversation-classify" + UTTERANCE_CLASSIFY = "utterance-classify" EXTRACT = "extract" - EXTRACT_NORMALIZE = "extract_normalize" - PII_EXTRACT = "pii_extract" + EXTRACT_NORMALIZE = "extract-normalize" + PII_EXTRACT = "pii-extract" + TEXT_GENERATION = "text-generation" + JSON = "json" """ :ivar operator_type: @@ -44,6 +47,7 @@ class OperatorType(object): :ivar label_probabilities: The labels probabilities. This might be available on conversation classify model outputs. :ivar extract_results: List of text extraction results. This might be available on classify-extract model outputs. :ivar text_generation_results: Output of a text generation operator for example Conversation Sumamary. + :ivar json_results: :ivar transcript_sid: A 34 character string that uniquely identifies this Transcript. :ivar url: The URL of this resource. """ @@ -84,6 +88,7 @@ def __init__( self.text_generation_results: Optional[Dict[str, object]] = payload.get( "text_generation_results" ) + self.json_results: Optional[Dict[str, object]] = payload.get("json_results") self.transcript_sid: Optional[str] = payload.get("transcript_sid") self.url: Optional[str] = payload.get("url") @@ -91,6 +96,7 @@ def __init__( "transcript_sid": transcript_sid, "operator_sid": operator_sid or self.operator_sid, } + self._context: Optional[OperatorResultContext] = None @property @@ -137,6 +143,34 @@ async def fetch_async( redacted=redacted, ) + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,18 +204,15 @@ def __init__(self, version: Version, transcript_sid: str, operator_sid: str): ) ) - def fetch( - self, redacted: Union[bool, object] = values.unset - ) -> OperatorResultInstance: + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: """ - Fetch the OperatorResultInstance - - :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + Internal helper for fetch operation - :returns: The fetched OperatorResultInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } @@ -191,10 +222,21 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = self._fetch(redacted=redacted) return OperatorResultInstance( self._version, payload, @@ -202,18 +244,34 @@ def fetch( operator_sid=self._solution["operator_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, redacted: Union[bool, object] = values.unset - ) -> OperatorResultInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the OperatorResultInstance + Fetch the OperatorResultInstance and return response metadata :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. - :returns: The fetched OperatorResultInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } @@ -223,10 +281,21 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) return OperatorResultInstance( self._version, payload, @@ -234,6 +303,25 @@ async def fetch_async( operator_sid=self._solution["operator_sid"], ) + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance and return response metadata + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -252,6 +340,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorResultInstance: :param payload: Payload response from the API """ + return OperatorResultInstance( self._version, payload, transcript_sid=self._solution["transcript_sid"] ) @@ -339,6 +428,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, redacted: Union[bool, object] = values.unset, @@ -360,6 +505,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( redacted=redacted, @@ -389,6 +535,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -398,6 +545,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, redacted: Union[bool, object] = values.unset, @@ -432,7 +635,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) async def page_async( self, @@ -468,7 +671,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorResultPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> OperatorResultPage: """ @@ -480,7 +759,7 @@ def get_page(self, target_url: str) -> OperatorResultPage: :returns: Page of OperatorResultInstance """ response = self._version.domain.twilio.request("GET", target_url) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> OperatorResultPage: """ @@ -492,7 +771,7 @@ async def get_page_async(self, target_url: str) -> OperatorResultPage: :returns: Page of OperatorResultInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) def get(self, operator_sid: str) -> OperatorResultContext: """ diff --git a/twilio/rest/intelligence/v2/transcript/sentence.py b/twilio/rest/intelligence/v2/transcript/sentence.py index f4fb0b3b92..ee11548693 100644 --- a/twilio/rest/intelligence/v2/transcript/sentence.py +++ b/twilio/rest/intelligence/v2/transcript/sentence.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,15 +43,11 @@ def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: st self.sentence_index: Optional[int] = deserialize.integer( payload.get("sentence_index") ) - self.start_time: Optional[float] = deserialize.decimal( - payload.get("start_time") - ) - self.end_time: Optional[float] = deserialize.decimal(payload.get("end_time")) + self.start_time: Optional[str] = payload.get("start_time") + self.end_time: Optional[str] = payload.get("end_time") self.transcript: Optional[str] = payload.get("transcript") self.sid: Optional[str] = payload.get("sid") - self.confidence: Optional[float] = deserialize.decimal( - payload.get("confidence") - ) + self.confidence: Optional[str] = payload.get("confidence") self.words: Optional[List[Dict[str, object]]] = payload.get("words") self._solution = { @@ -75,6 +72,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SentenceInstance: :param payload: Payload response from the API """ + return SentenceInstance( self._version, payload, transcript_sid=self._solution["transcript_sid"] ) @@ -172,6 +170,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SentenceInstance and returns headers from first page + + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SentenceInstance and returns headers from first page + + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, redacted: Union[bool, object] = values.unset, @@ -195,6 +257,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( redacted=redacted, @@ -227,6 +290,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -237,6 +301,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SentenceInstance and returns headers from first page + + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SentenceInstance and returns headers from first page + + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, redacted: Union[bool, object] = values.unset, @@ -274,7 +400,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) async def page_async( self, @@ -313,7 +439,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SentencePage, status code, and headers + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SentencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SentencePage, status code, and headers + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SentencePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SentencePage: """ @@ -325,7 +533,7 @@ def get_page(self, target_url: str) -> SentencePage: :returns: Page of SentenceInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SentencePage: """ @@ -337,7 +545,7 @@ async def get_page_async(self, target_url: str) -> SentencePage: :returns: Page of SentenceInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/intelligence/v3/__init__.py b/twilio/rest/intelligence/v3/__init__.py new file mode 100644 index 0000000000..4aff29efe0 --- /dev/null +++ b/twilio/rest/intelligence/v3/__init__.py @@ -0,0 +1,90 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.intelligence.v3.configuration import ConfigurationList +from twilio.rest.intelligence.v3.conversation import ConversationList +from twilio.rest.intelligence.v3.operator import OperatorList +from twilio.rest.intelligence.v3.operator_result import OperatorResultList +from twilio.rest.intelligence.v3.rule_execution import RuleExecutionList +from twilio.rest.intelligence.v3.version import VersionList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Intelligence + + :param domain: The Twilio.intelligence domain + """ + super().__init__(domain, "v3") + self._configurations: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._operators: Optional[OperatorList] = None + self._operator_results: Optional[OperatorResultList] = None + self._rule_executions: Optional[RuleExecutionList] = None + + @property + def configurations(self) -> ConfigurationList: + if self._configurations is None: + self._configurations = ConfigurationList(self) + return self._configurations + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def operators(self) -> OperatorList: + if self._operators is None: + self._operators = OperatorList(self) + return self._operators + + @property + def operator_results(self) -> OperatorResultList: + if self._operator_results is None: + self._operator_results = OperatorResultList(self) + return self._operator_results + + @property + def rule_executions(self) -> RuleExecutionList: + if self._rule_executions is None: + self._rule_executions = RuleExecutionList(self) + return self._rule_executions + + def versions(self, id: str, version_id: str = None): + """ + Access the VersionList resource + + :param id: The unique identifier (TTID) of the Language Operator. + + :param version_id: Optional instance ID to directly access VersionContext + :returns: VersionList instance if version_id is None, otherwise VersionContext + """ + list_instance = VersionList(self, id) + if version_id is not None: + return list_instance(version_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/configuration.py b/twilio/rest/intelligence/v3/configuration.py new file mode 100644 index 0000000000..d67f2057b5 --- /dev/null +++ b/twilio/rest/intelligence/v3/configuration.py @@ -0,0 +1,1333 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConfigurationInstance(InstanceResource): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar account_id: The ID of the Account that created the Intelligence Configuration. + :ivar id: The unique identifier for the Intelligence Configuration. Assigned by Twilio (TTID). + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar version: The numeric version of the Intelligence Configuration. Automatically incremented with each update on the resource, used to ensure integrity when updating the Configuration. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + :ivar date_created: Timestamp of when the Intelligence Configuration was created. + :ivar date_updated: Timestamp of when the Intelligence Configuration was last updated. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.account_id: Optional[str] = payload.get("accountId") + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + update_configuration_request=update_configuration_request, + ) + + async def update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + update_configuration_request=update_configuration_request, + ) + + def update_with_http_info( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_configuration_request=update_configuration_request, + ) + + async def update_with_http_info_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_configuration_request=update_configuration_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param id: The unique identifier of the Intelligence Configuration. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Configurations/{id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConfigurationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + update_configuration_request=update_configuration_request + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Update the ConfigurationInstance and return response metadata + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_configuration_request=update_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param update_configuration_request: + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + update_configuration_request=update_configuration_request + ) + return ConfigurationInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, update_configuration_request: UpdateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param update_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_configuration_request=update_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfigurationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConfigurationInstance: + """ + Build an instance of ConfigurationInstance + + :param payload: Payload response from the API + """ + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfigurationList(ListResource): + + class Action(object): + """ + :ivar type: The type of Action to be performed after the Rule is triggered. Supported Actions are: - `WEBHOOK`: A webhook Action sends an HTTP request to a specified URL with Rule execution results. + :ivar method: The HTTP method to be used when performing the Action. Must be set to `POST`. + :ivar url: The URL endpoint where the Action will send the HTTP request containing the Rule execution results. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ConfigurationInstance.str"] = payload.get("type") + self.method: Optional["ConfigurationInstance.str"] = payload.get("method") + self.url: Optional[str] = payload.get("url") + + def to_dict(self): + return { + "type": self.type, + "method": self.method, + "url": self.url, + } + + class Context(object): + """ + :ivar memory: + :ivar knowledge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.memory: Optional[ConfigurationList.ContextMemory] = payload.get( + "memory" + ) + self.knowledge: Optional[ConfigurationList.ContextKnowledge] = payload.get( + "knowledge" + ) + + def to_dict(self): + return { + "memory": self.memory.to_dict() if self.memory is not None else None, + "knowledge": ( + self.knowledge.to_dict() if self.knowledge is not None else None + ), + } + + class ContextKnowledge(object): + """ + :ivar bases: Specifies the Knowledge Base(s) and corresponding Source(s) to pass to Language Operators in this Rule as context. Only applied to Language Operators that have Knowledge as a context source enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.bases: Optional[List[str]] = payload.get("bases") + + def to_dict(self): + return { + "bases": self.bases, + } + + class ContextMemory(object): + """ + :ivar enabled: When set to `true`, allows this Intelligence Configuration Rule to pass the Profile into attached Language Operators. The profile is only passed to Language Operators that have Memory as a context source enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class CreateConfigurationRequest(object): + """ + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. To create an Intelligence Configuration without any Rules configured yet, pass an empty array (`\"rules\": []`). The Configuration will not execute any Language Operators until at least one Rule has been added. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.rules: Optional[List[ConfigurationList.RuleCreationRequestPayload]] = ( + payload.get("rules") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "rules": ( + [rules.to_dict() for rules in self.rules] + if self.rules is not None + else None + ), + } + + class Operator(object): + """ + :ivar id: The unique identifier for the Language Operator to be executed by the Rule. Assigned by Twilio (TTID). + :ivar version: The specific version of the Language Operator to execute. When provided, the Rule will use this exact version of the Operator. When omitted, the latest active version of the Operator is used at execution time. + :ivar parameters: Key-value mapping for parameters defined as part of the Operator schema. The key and value passed by the Rule must match the name and data type of the parameter defined in the Operator, respectively. These parameters will customize the behavior of the Operator when executed by the Rule via runtime substitution into the prompt. Note: For parameters of type `knowledge_base_and_source_ids`, the value must be passed in the following format: `knowledge_base_id:knowledge_source_id`. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.version: Optional[int] = payload.get("version") + self.parameters: Optional[Dict[str, object]] = payload.get("parameters") + + def to_dict(self): + return { + "id": self.id, + "version": self.version, + "parameters": self.parameters, + } + + class RuleCreationRequestPayload(object): + """ + :ivar operators: List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + :ivar triggers: List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + :ivar actions: List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + :ivar context: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.operators: Optional[List[ConfigurationList.Operator]] = payload.get( + "operators" + ) + self.triggers: Optional[List[ConfigurationList.Trigger]] = payload.get( + "triggers" + ) + self.actions: Optional[List[ConfigurationList.Action]] = payload.get( + "actions" + ) + self.context: Optional[ConfigurationList.Context] = payload.get("context") + + def to_dict(self): + return { + "operators": ( + [operators.to_dict() for operators in self.operators] + if self.operators is not None + else None + ), + "triggers": ( + [triggers.to_dict() for triggers in self.triggers] + if self.triggers is not None + else None + ), + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + } + + class RuleUpdateRequestPayload(object): + """ + :ivar id: Optional field used when updating an existing Rule within an Intelligence Configuration. When provided, the Rule with this `id` is updated; when omitted, a new Rule is created. + :ivar operators: List of Operators to be executed by the Rule. Minimum of one (1) and maximum of five (5) Operators allowed per Rule. + :ivar triggers: List of Triggers that determine when to activate the Rule. Maximum of one (1) Trigger allowed per Rule. + :ivar actions: List of Actions to be performed after the Rule is triggered. Maximum of two (2) Actions allowed per Rule. + :ivar context: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.operators: Optional[List[ConfigurationList.Operator]] = payload.get( + "operators" + ) + self.triggers: Optional[List[ConfigurationList.Trigger]] = payload.get( + "triggers" + ) + self.actions: Optional[List[ConfigurationList.Action]] = payload.get( + "actions" + ) + self.context: Optional[ConfigurationList.Context] = payload.get("context") + + def to_dict(self): + return { + "id": self.id, + "operators": ( + [operators.to_dict() for operators in self.operators] + if self.operators is not None + else None + ), + "triggers": ( + [triggers.to_dict() for triggers in self.triggers] + if self.triggers is not None + else None + ), + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + } + + class Trigger(object): + """ + :ivar on: The conversational lifecycle event that will activate execution of the Rule. Available values are: - `COMMUNICATION`: Trigger the Rule on each communication within the Conversation. - `CONVERSATION_END`: Trigger the Rule when the Conversation moves to the `closed` state - `CONVERSATION_INACTIVE`: Trigger the Rule when the Conversation moves to `inactive` state + :ivar parameters: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.on: Optional["ConfigurationInstance.str"] = payload.get("on") + self.parameters: Optional[ConfigurationList.TriggerParameters] = ( + payload.get("parameters") + ) + + def to_dict(self): + return { + "on": self.on, + "parameters": ( + self.parameters.to_dict() if self.parameters is not None else None + ), + } + + class TriggerParameters(object): + """ + :ivar count: When `on` is set to `COMMUNICATION`, this value controls how often the Rule should run. A value of `1` executes the Rule for every communication event. Higher values delay execution until the specified number of communications have occurred since the last execution. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.count: Optional[int] = payload.get("count") + + def to_dict(self): + return { + "count": self.count, + } + + class UpdateConfigurationRequest(object): + """ + :ivar display_name: The display name of the Intelligence Configuration describing its purpose. + :ivar description: The description of the Intelligence Configuration further explaining its purpose. + :ivar rules: List of Intelligence Configuration Rules that govern when and how Language Operators run. Each Rule represents a bundle of Operators, Triggers, Context, and Actions to be executed by the Intelligence Configuration on a Conversation. A maximum of five (5) Rules are allowed per Intelligence Configuration. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.rules: Optional[List[ConfigurationList.RuleUpdateRequestPayload]] = ( + payload.get("rules") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "rules": ( + [rules.to_dict() for rules in self.rules] + if self.rules is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Configurations" + + def _create( + self, create_configuration_request: CreateConfigurationRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_configuration_request: CreateConfigurationRequest + ) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param create_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = self._create( + create_configuration_request=create_configuration_request + ) + return ConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, create_configuration_request: CreateConfigurationRequest + ) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param create_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_configuration_request=create_configuration_request + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> ConfigurationInstance: + """ + Asynchronously create the ConfigurationInstance + + :param create_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = await self._create_async( + create_configuration_request=create_configuration_request + ) + return ConfigurationInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_configuration_request: CreateConfigurationRequest + ) -> ApiResponse: + """ + Asynchronously create the ConfigurationInstance and return response metadata + + :param create_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_configuration_request=create_configuration_request + ) + instance = ConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfigurationInstance]: + """ + Streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfigurationInstance]: + """ + Asynchronously streams ConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Lists ConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfigurationInstance]: + """ + Asynchronously lists ConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfigurationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ConfigurationPage: + """ + Asynchronously retrieve a single page of ConfigurationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of ConfigurationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfigurationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConfigurationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConfigurationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConfigurationPage: + """ + Retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConfigurationPage: + """ + Asynchronously retrieve a specific page of ConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfigurationPage(self._version, response) + + def get(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: The unique identifier of the Intelligence Configuration. + """ + return ConfigurationContext(self._version, id=id) + + def __call__(self, id: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param id: The unique identifier of the Intelligence Configuration. + """ + return ConfigurationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/conversation.py b/twilio/rest/intelligence/v3/conversation.py new file mode 100644 index 0000000000..62faa0809b --- /dev/null +++ b/twilio/rest/intelligence/v3/conversation.py @@ -0,0 +1,1016 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationInstance(InstanceResource): + + class Channel(object): + VOICE = "VOICE" + SMS = "SMS" + RCS = "RCS" + EMAIL = "EMAIL" + WHATSAPP = "WHATSAPP" + CHAT = "CHAT" + API = "API" + SYSTEM = "SYSTEM" + + class ConversationStatus(object): + ACTIVE = "ACTIVE" + INACTIVE = "INACTIVE" + CLOSED = "CLOSED" + + """ + :ivar id: The `id` of the Conversation attached to the Operator Result. + :ivar account_id: The ID of the account that owns the Conversation. + :ivar name: Display name of the Conversation. + :ivar status: + :ivar created_at: Timestamp for when the Conversation was created. + :ivar updated_at: Timestamp for when the Conversation was last updated. + :ivar intelligence_configuration_ids: The Intelligence Configuration(s) associated with the Conversation. + :ivar conversation_configuration_id: The `id` of the Configuration for a Conversation. + :ivar channels: The communication channel(s) included in the Conversation. + :ivar channel_ids: The underlying channel resource `id`s associated with this Conversation, such as a Call ID or Message ID. + :ivar participants: Metadata for Participants of the Conversation. + :ivar communications: Metadata for the Communications that make up the Conversation. + :ivar operator_result_ids: List of Operator Result IDs generated from this Conversation. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.name: Optional[str] = payload.get("name") + self.status: Optional["ConversationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.intelligence_configuration_ids: Optional[List[str]] = payload.get( + "intelligenceConfigurationIds" + ) + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.channels: Optional[List[Enumstr]] = payload.get("channels") + self.channel_ids: Optional[List[str]] = payload.get("channelIds") + self.participants: Optional[List[str]] = payload.get("participants") + self.communications: Optional[List[str]] = payload.get("communications") + self.operator_result_ids: Optional[List[str]] = payload.get("operatorResultIds") + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param id: The unique identifier of the conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Conversations/{id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConversationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def stream( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param datetime created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param datetime created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param str status: Filter by Conversation status. + :param str channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param List[str] channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param str conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param List[str] intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param List[str] operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + created_at_before=created_at_before, + created_at_after=created_at_after, + status=status, + channel_id=channel_id, + channels=channels, + conversation_configuration_id=conversation_configuration_id, + intelligence_configuration_ids=intelligence_configuration_ids, + operator_ids=operator_ids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :returns: Page of ConversationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :returns: Page of ConversationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + created_at_before: Union[datetime, object] = values.unset, + created_at_after: Union[datetime, object] = values.unset, + status: Union[str, object] = values.unset, + channel_id: Union[str, object] = values.unset, + channels: Union[List[str], object] = values.unset, + conversation_configuration_id: Union[str, object] = values.unset, + intelligence_configuration_ids: Union[List[str], object] = values.unset, + operator_ids: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param created_at_before: Filter by Conversations created before this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param created_at_after: Filter by Conversations created after this timestamp. The maximum allowed time range between `createdAtBefore` and `createdAtAfter` is 31 days. + :param status: Filter by Conversation status. + :param channel_id: Filters Conversations by the underlying channel resource ID, such as a Call ID or Message ID. + :param channels: Filters Conversations that include one or more of the specified communication channels (`OR` match). + :param conversation_configuration_id: The configuration `id` used to generate the Conversation. + :param intelligence_configuration_ids: Filters Conversations activated by one or more of the specified Intelligence Configuration IDs (`OR` match). + :param operator_ids: Filters Conversations to those where at least one of the specified Language Operators was executed (`OR` match). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "createdAtBefore": serialize.iso8601_datetime(created_at_before), + "createdAtAfter": serialize.iso8601_datetime(created_at_after), + "status": status, + "channelId": channel_id, + "channels": serialize.map(channels, lambda e: e), + "conversationConfigurationId": conversation_configuration_id, + "intelligenceConfigurationIds": serialize.map( + intelligence_configuration_ids, lambda e: e + ), + "operatorIds": serialize.map(operator_ids, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: The unique identifier of the conversation. + """ + return ConversationContext(self._version, id=id) + + def __call__(self, id: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param id: The unique identifier of the conversation. + """ + return ConversationContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/operator.py b/twilio/rest/intelligence/v3/operator.py new file mode 100644 index 0000000000..cbd7499a58 --- /dev/null +++ b/twilio/rest/intelligence/v3/operator.py @@ -0,0 +1,1246 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class OperatorInstance(InstanceResource): + + class OperatorAuthor(object): + SELF = "SELF" + TWILIO = "TWILIO" + + class OperatorOutputFormat(object): + TEXT = "TEXT" + JSON = "JSON" + CLASSIFICATION = "CLASSIFICATION" + + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar version: Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__( + self, version: Version, payload: ResponseResource, id: Optional[str] = None + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.author: Optional["OperatorInstance.OperatorAuthor"] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["OperatorInstance.OperatorOutputFormat"] = ( + payload.get("outputFormat") + ) + self.output_schema: Optional[Dict[str, object]] = payload.get("outputSchema") + self.training_examples: Optional[List[OperatorList.OperatorTrainingExample]] = ( + payload.get("trainingExamples") + ) + self.context: Optional[OperatorList.OperatorContext] = payload.get("context") + self.parameters: Optional[Dict[str, OperatorParameter]] = payload.get( + "parameters" + ) + + # Only set _solution if path params are provided (not None) + if id is not None: + self._solution = { + "id": id, + } + + self._context: Optional[OperatorContext] = None + + @property + def _proxy(self) -> "OperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorContext for this OperatorInstance + """ + if self._context is None: + self._context = OperatorContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "OperatorInstance": + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorInstance": + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> "OperatorInstance": + """ + Update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + return self._proxy.update( + language_operator=language_operator, + if_match=if_match, + ) + + async def update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> "OperatorInstance": + """ + Asynchronous coroutine to update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + return await self._proxy.update_async( + language_operator=language_operator, + if_match=if_match, + ) + + def update_with_http_info( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OperatorInstance with HTTP info + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + language_operator=language_operator, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OperatorInstance with HTTP info + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + language_operator=language_operator, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the OperatorContext + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Operators/{id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = self._fetch() + return OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> OperatorInstance: + """ + Update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + payload, _, _ = self._update( + language_operator=language_operator, if_match=if_match + ) + return OperatorInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OperatorInstance and return response metadata + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + language_operator=language_operator, if_match=if_match + ) + instance = OperatorInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> OperatorInstance: + """ + Asynchronous coroutine to update the OperatorInstance + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: The updated OperatorInstance + """ + payload, _, _ = await self._update_async( + language_operator=language_operator, if_match=if_match + ) + return OperatorInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + language_operator: LanguageOperator, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OperatorInstance and return response metadata + + :param language_operator: Full replacement of a Language Operator configuration + :param if_match: Current ETag/version required for conditional update + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + language_operator=language_operator, if_match=if_match + ) + instance = OperatorInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorInstance: + """ + Build an instance of OperatorInstance + + :param payload: Payload response from the API + """ + + return OperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorList(ListResource): + + class LanguageOperator(object): + """ + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar version: Numeric Operator version. Automatically incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.author: Optional[OperatorAuthorEnum] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["OperatorInstance.OperatorOutputFormat"] = ( + payload.get("outputFormat") + ) + self.output_schema: Optional[Dict[str, object]] = payload.get( + "outputSchema" + ) + self.training_examples: Optional[ + List[OperatorList.OperatorTrainingExample] + ] = payload.get("trainingExamples") + self.context: Optional[OperatorList.OperatorContext] = payload.get( + "context" + ) + self.parameters: Optional[Dict[str, OperatorParameter]] = payload.get( + "parameters" + ) + + def to_dict(self): + return { + "id": self.id, + "displayName": self.display_name, + "description": self.description, + "version": self.version, + "author": self.author, + "prompt": self.prompt, + "outputFormat": self.output_format, + "outputSchema": self.output_schema, + "trainingExamples": ( + [ + training_examples.to_dict() + for training_examples in self.training_examples + ] + if self.training_examples is not None + else None + ), + "context": self.context.to_dict() if self.context is not None else None, + "parameters": ( + {k: v.to_dict() for k, v in self.parameters.items()} + if self.parameters is not None + else None + ), + } + + class OperatorContext(object): + """ + :ivar memory: + :ivar knowledge: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.memory: Optional[OperatorList.OperatorContextMemory] = payload.get( + "memory" + ) + self.knowledge: Optional[OperatorList.OperatorContextKnowledge] = ( + payload.get("knowledge") + ) + + def to_dict(self): + return { + "memory": self.memory.to_dict() if self.memory is not None else None, + "knowledge": ( + self.knowledge.to_dict() if self.knowledge is not None else None + ), + } + + class OperatorContextKnowledge(object): + """ + :ivar enabled: Set to true to allow access to Knowledge Sources at runtime. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class OperatorContextMemory(object): + """ + :ivar enabled: Set to true to allow access to Memory at runtime. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.enabled: Optional[bool] = payload.get("enabled") + + def to_dict(self): + return { + "enabled": self.enabled, + } + + class OperatorTrainingExample(object): + """ + :ivar input: A sample input text that demonstrates the type of content the Operator processes. + :ivar output: The expected output corresponding to the provided input example. This value must be consistent with the defined `output_format` and `output_schema` of the Operator. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.input: Optional[str] = payload.get("input") + self.output: Optional[str] = payload.get("output") + + def to_dict(self): + return { + "input": self.input, + "output": self.output, + } + + def __init__(self, version: Version): + """ + Initialize the OperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Operators" + + def _create(self, language_operator: LanguageOperator) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, language_operator: LanguageOperator) -> OperatorInstance: + """ + Create the OperatorInstance + + :param language_operator: Create Language Operator request + + :returns: The created OperatorInstance + """ + payload, _, _ = self._create(language_operator=language_operator) + return OperatorInstance(self._version, payload) + + def create_with_http_info(self, language_operator: LanguageOperator) -> ApiResponse: + """ + Create the OperatorInstance and return response metadata + + :param language_operator: Create Language Operator request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + language_operator=language_operator + ) + instance = OperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, language_operator: LanguageOperator) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = language_operator.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, language_operator: LanguageOperator + ) -> OperatorInstance: + """ + Asynchronously create the OperatorInstance + + :param language_operator: Create Language Operator request + + :returns: The created OperatorInstance + """ + payload, _, _ = await self._create_async(language_operator=language_operator) + return OperatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, language_operator: LanguageOperator + ) -> ApiResponse: + """ + Asynchronously create the OperatorInstance and return response metadata + + :param language_operator: Create Language Operator request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + language_operator=language_operator + ) + instance = OperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorInstance]: + """ + Streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorInstance]: + """ + Asynchronously streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Asynchronously lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorPage: + """ + Retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorPage: + """ + Asynchronously retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> OperatorPage: + """ + Retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorPage: + """ + Asynchronously retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorPage(self._version, response) + + def get(self, id: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param id: The unique identifier (TTID) of the Language Operator. + """ + return OperatorContext(self._version, id=id) + + def __call__(self, id: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param id: The unique identifier (TTID) of the Language Operator. + """ + return OperatorContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/operator_result.py b/twilio/rest/intelligence/v3/operator_result.py new file mode 100644 index 0000000000..1f649795d0 --- /dev/null +++ b/twilio/rest/intelligence/v3/operator_result.py @@ -0,0 +1,933 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class OperatorResultInstance(InstanceResource): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + :ivar output_format: The output format set on the Operator that generated this result. Determines the structure of the `result` object. + :ivar id: A unique identifier for the Operator Result. Assigned by Twilio (TTID). + :ivar account_id: The ID of the Account that created the Language Operator. + :ivar intelligence_configuration: + :ivar conversation_id: The `id` of the Conversation attached to the Operator Result. + :ivar operator: + :ivar date_created: Timestamp for when the Operator Result was created. + :ivar reference_ids: The `id`s of objects related to this Operator Result. + :ivar execution_details: + :ivar metadata: + :ivar result: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + operator_result_id: Optional[str] = None, + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + self.output_format: Optional[str] = payload.get("outputFormat") + self.id: Optional[str] = payload.get("id") + self.account_id: Optional[str] = payload.get("accountId") + self.intelligence_configuration: Optional[ + IntelligenceConfigurationReference + ] = payload.get("intelligenceConfiguration") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.operator: Optional[OperatorReference] = payload.get("operator") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.reference_ids: Optional[List[str]] = payload.get("referenceIds") + self.execution_details: Optional[ExecutionDetails] = payload.get( + "executionDetails" + ) + self.metadata: Optional[OperatorResultsResponseBaseMetadata] = payload.get( + "metadata" + ) + self.result: Optional[ExtractionResultResult] = payload.get("result") + + # Only set _solution if path params are provided (not None) + if operator_result_id is not None: + self._solution = { + "operator_result_id": operator_result_id, + } + + self._context: Optional[OperatorResultContext] = None + + @property + def _proxy(self) -> "OperatorResultContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorResultContext for this OperatorResultInstance + """ + if self._context is None: + self._context = OperatorResultContext( + self._version, + operator_result_id=self._solution["operator_result_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "OperatorResultInstance": + """ + Fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorResultInstance": + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorResultContext(InstanceContext): + + def __init__(self, version: Version, operator_result_id: str): + """ + Initialize the OperatorResultContext + + :param version: Version that contains the resource + :param operator_result_id: Operator Result id (TTID) + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operator_result_id": operator_result_id, + } + self._uri = "/OperatorResults/{operator_result_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperatorResultInstance: + """ + Fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = self._fetch() + return OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperatorResultInstance: + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + + :returns: The fetched OperatorResultInstance + """ + payload, _, _ = await self._fetch_async() + return OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperatorResultInstance( + self._version, + payload, + operator_result_id=self._solution["operator_result_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorResultPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorResultInstance: + """ + Build an instance of OperatorResultInstance + + :param payload: Payload response from the API + """ + + return OperatorResultInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorResultList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorResultList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/OperatorResults" + + def stream( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorResultInstance]: + """ + Streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorResultInstance]: + """ + Asynchronously streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Asynchronously lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorResultInstance and returns headers from first page + + + :param str conversation_id: Filter Operator Results by attached Conversation `id`. + :param str intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param str operator_id: Filter Operator Results by Language Operator `id`. + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + conversation_id=conversation_id, + intelligence_configuration_id=intelligence_configuration_id, + operator_id=operator_id, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorResultPage: + """ + Retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> OperatorResultPage: + """ + Asynchronously retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorResultPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + intelligence_configuration_id: Union[str, object] = values.unset, + operator_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param conversation_id: Filter Operator Results by attached Conversation `id`. + :param intelligence_configuration_id: Filter Operator Results by Intelligence Configuration `id` used to generate them. + :param operator_id: Filter Operator Results by Language Operator `id`. + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorResultPage, status code, and headers + """ + data = values.of( + { + "conversationId": conversation_id, + "intelligenceConfigurationId": intelligence_configuration_id, + "operatorId": operator_id, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorResultPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> OperatorResultPage: + """ + Retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorResultPage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorResultPage: + """ + Asynchronously retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorResultPage(self._version, response) + + def get(self, operator_result_id: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_result_id: Operator Result id (TTID) + """ + return OperatorResultContext( + self._version, operator_result_id=operator_result_id + ) + + def __call__(self, operator_result_id: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_result_id: Operator Result id (TTID) + """ + return OperatorResultContext( + self._version, operator_result_id=operator_result_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/rule_execution.py b/twilio/rest/intelligence/v3/rule_execution.py new file mode 100644 index 0000000000..a365eab628 --- /dev/null +++ b/twilio/rest/intelligence/v3/rule_execution.py @@ -0,0 +1,199 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RuleExecutionInstance(InstanceResource): + """ + :ivar code: Twilio-specific error code + :ivar message: A human readable error message + :ivar http_status_code: HTTP response status code + :ivar user_error: Whether the error is a user error (true) or a system error (false) + :ivar params: A map of parameters related to the error, for example, a `params.twilioErrorCodeUrl` might hold a URL or link to additional information + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.http_status_code: Optional[int] = payload.get("httpStatusCode") + self.user_error: Optional[bool] = payload.get("userError") + self.params: Optional[Dict[str, str]] = payload.get("params") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class RuleExecutionList(ListResource): + + class CreateRuleExecutionRequest(object): + """ + :ivar intelligence_configuration_id: The Intelligence Configuration identifier to execute the Rule within. + :ivar rule_id: The rule identifier to execute within the selected Intelligence Configuration. + :ivar conversation_id: The Conversation identifier to execute the Rule against. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.intelligence_configuration_id: Optional[str] = payload.get( + "intelligenceConfigurationId" + ) + self.rule_id: Optional[str] = payload.get("ruleId") + self.conversation_id: Optional[str] = payload.get("conversationId") + + def to_dict(self): + return { + "intelligenceConfigurationId": self.intelligence_configuration_id, + "ruleId": self.rule_id, + "conversationId": self.conversation_id, + } + + def __init__(self, version: Version): + """ + Initialize the RuleExecutionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RuleExecutions" + + def _create( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_rule_execution_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> RuleExecutionInstance: + """ + Create the RuleExecutionInstance + + :param create_rule_execution_request: + + :returns: The created RuleExecutionInstance + """ + payload, _, _ = self._create( + create_rule_execution_request=create_rule_execution_request + ) + return RuleExecutionInstance(self._version, payload) + + def create_with_http_info( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> ApiResponse: + """ + Create the RuleExecutionInstance and return response metadata + + :param create_rule_execution_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_rule_execution_request=create_rule_execution_request + ) + instance = RuleExecutionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_rule_execution_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> RuleExecutionInstance: + """ + Asynchronously create the RuleExecutionInstance + + :param create_rule_execution_request: + + :returns: The created RuleExecutionInstance + """ + payload, _, _ = await self._create_async( + create_rule_execution_request=create_rule_execution_request + ) + return RuleExecutionInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_rule_execution_request: CreateRuleExecutionRequest + ) -> ApiResponse: + """ + Asynchronously create the RuleExecutionInstance and return response metadata + + :param create_rule_execution_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_rule_execution_request=create_rule_execution_request + ) + instance = RuleExecutionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/version.py b/twilio/rest/intelligence/v3/version.py new file mode 100644 index 0000000000..b283dbf541 --- /dev/null +++ b/twilio/rest/intelligence/v3/version.py @@ -0,0 +1,753 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Conversational Intelligence API + The Conversational Intelligence API includes resources to create and manage intelligence configurations, define and run language operators, and retrieve processed conversations and operator results. * Use the Configurations resource to create and manage intelligence configurations and define rules that control how and when language operators analyze and transform conversations. * Use the Operators resource to create custom language operators or retrieve Twilio-author and custom operators. * Use the Conversations resource to retrieve conversations processed with an intelligence configuration, and the OperatorResults resource to retrieve language operator results for those conversations. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class VersionInstance(InstanceResource): + + class OperatorAuthor(object): + SELF = "SELF" + TWILIO = "TWILIO" + + class OperatorOutputFormat(object): + TEXT = "TEXT" + JSON = "JSON" + CLASSIFICATION = "CLASSIFICATION" + + class OperatorVersionStatus(object): + PREVIEW = "PREVIEW" + ACTIVE = "ACTIVE" + DEPRECATED = "DEPRECATED" + RETIRED = "RETIRED" + + """ + :ivar version: The numeric version number. + :ivar status: + :ivar date_created: Timestamp of when this version was created. + :ivar date_deprecated: Timestamp of when this version was deprecated. Present when status is `DEPRECATED` or `RETIRED`. + :ivar retirement_date: Scheduled retirement date for this version. Present when status is `DEPRECATED`. + :ivar date_retired: Timestamp of when this version was retired. Present when status is `RETIRED`. + :ivar id: The unique identifier for the Language Operator. Assigned by Twilio (TTID). + :ivar display_name: Display name of the Language Operator describing its purpose. + :ivar description: Description of the Language Operator further explaining its purpose. + :ivar author: + :ivar prompt: The natural language instructions used by the operator to analyze the conversation. Within the prompt, users can reference parameters using the `{{parameters.[param_name]}}` syntax. Parameter values are provided to the Operator by the Intelligence Configuration Rule at runtime. **Note**: Prompts will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their prompts omitted from the API. + :ivar output_format: + :ivar output_schema: Required for `JSON` output only. this will be set to a JSON Schema object describing the properties & data types of the response. Please see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas Will include the following keywords: - `type` : Must be set to `object` - `properties`: An object containing the property names and their data types you would like the LLM to return Additional details on JSON output formatting: - The root level `type` of a JSON schema must be set to `object` - The following property data types are supported : `string`, `number`, `boolean`, `integer`, `object`, `array`, `anyOf` - Definitions with `$defs` / `$ref` are supported - Max 100 object properties and 10 levels of nesting are supported - Max 1000 enum values across all enum properties are supported - Notable JSON Schema keywords not supported include: - For `strings`: `minLength`, `maxLength` - For `objects`: `patternProperties`, `unevaluatedProperties`, `propertyNames`, `minProperties`, `maxProperties` - For `arrays`: `unevaluatedItems`, `contains`, `minContains`, `maxContains`, `uniqueItems` - Structured Operator Results will be returned in the same order as the ordering of keys in the schema - In the event an Operator execution request is refused for safety reasons the Operator Result API response will include a new field called `refusal` to indicate that the LLM refused to fulfill the request - Twilio will automatically set `additionalProperties` to false and specify all provided fields as required (constraints of Structured Outputs). You don't need to pass these fields as part of your JSON schema. Twilio will automatically overwrite any user-provided values for these fields. + :ivar training_examples: An array of example input/output pairs used to illustrate the intended behavior of the Language Operator. These examples help guide the model's understanding of expected input–output relationships and improve consistency during evaluation and testing. **Note**: Training examples will only be exposed for Custom Operators (`author` = `SELF`). Twilio-authored Operators (`author` = `TWILIO`) will have their training examples omitted from the API. + :ivar context: + :ivar parameters: Defines the schema of the parameters that are provided when running the operator, including required and optional values that determine the operator's behavior. The values of the parameters themselves are passed in by the attached Intelligence Configuration. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + id: str, + resource_version: Optional[int] = None, + ): + super().__init__(version) + + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.status: Optional["VersionInstance.OperatorVersionStatus"] = payload.get( + "status" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_deprecated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateDeprecated") + ) + self.retirement_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("retirementDate") + ) + self.date_retired: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateRetired") + ) + self.id: Optional[str] = payload.get("id") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.author: Optional["VersionInstance.OperatorAuthor"] = payload.get("author") + self.prompt: Optional[str] = payload.get("prompt") + self.output_format: Optional["VersionInstance.str"] = payload.get( + "outputFormat" + ) + self.output_schema: Optional[Dict[str, object]] = payload.get("outputSchema") + self.training_examples: Optional[List[str]] = payload.get("trainingExamples") + self.context: Optional[str] = payload.get("context") + self.parameters: Optional[Dict[str, str]] = payload.get("parameters") + + # Only set _solution if path params are provided (not None) + if id is not None or resource_version is not None: + self._solution = { + "id": id, + "resource_version": resource_version, + } + + self._context: Optional[VersionContext] = None + + @property + def _proxy(self) -> "VersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VersionContext for this VersionInstance + """ + if self._context is None: + self._context = VersionContext( + self._version, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return self._context + + def fetch(self) -> "VersionInstance": + """ + Fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VersionInstance": + """ + Asynchronous coroutine to fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VersionContext(InstanceContext): + + def __init__(self, version: Version, id: str, resource_version: int): + """ + Initialize the VersionContext + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + :param resource_version: The numeric version number of the Language Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + "resource_version": resource_version, + } + self._uri = "/ControlPlane/Operators/{id}/Versions/{resource_version}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VersionInstance: + """ + Fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + payload, _, _ = self._fetch() + return VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> VersionInstance: + """ + Asynchronous coroutine to fetch the VersionInstance + + + :returns: The fetched VersionInstance + """ + payload, _, _ = await self._fetch_async() + return VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VersionInstance( + self._version, + payload, + id=self._solution["id"], + resource_version=self._solution["resource_version"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class VersionPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> VersionInstance: + """ + Build an instance of VersionInstance + + :param payload: Payload response from the API + """ + + return VersionInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class VersionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the VersionList + + :param version: Version that contains the resource + :param id: The unique identifier (TTID) of the Language Operator. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/ControlPlane/Operators/{id}/Versions".format(**self._solution) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VersionInstance]: + """ + Streams VersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VersionInstance]: + """ + Asynchronously streams VersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VersionInstance]: + """ + Lists VersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VersionInstance]: + """ + Asynchronously lists VersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VersionInstance and returns headers from first page + + + :param str page_token: Token for pagination + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> VersionPage: + """ + Retrieve a single page of VersionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of VersionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VersionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> VersionPage: + """ + Asynchronously retrieve a single page of VersionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of resources to return + :param page_token: Token for pagination + :returns: Page of VersionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VersionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VersionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VersionPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: Token for pagination + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VersionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> VersionPage: + """ + Retrieve a specific page of VersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VersionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> VersionPage: + """ + Asynchronously retrieve a specific page of VersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VersionPage(self._version, response, solution=self._solution) + + def get(self, resource_version: int) -> VersionContext: + """ + Constructs a VersionContext + + :param resource_version: The numeric version number of the Language Operator. + """ + return VersionContext( + self._version, id=self._solution["id"], resource_version=resource_version + ) + + def __call__(self, resource_version: int) -> VersionContext: + """ + Constructs a VersionContext + + :param resource_version: The numeric version number of the Language Operator. + """ + return VersionContext( + self._version, id=self._solution["id"], resource_version=resource_version + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/ip_messaging/v1/credential.py b/twilio/rest/ip_messaging/v1/credential.py index 4aa6d3fc63..b363627051 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,56 +354,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -277,18 +465,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -307,13 +489,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -323,7 +503,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param friendly_name: :param certificate: @@ -334,6 +514,63 @@ async def update_async( :returns: The updated CredentialInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +588,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -375,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -399,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -408,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance - - :param type: - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -440,13 +732,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -457,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: @@ -469,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -487,12 +839,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -543,6 +962,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -562,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -588,6 +1058,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -596,6 +1067,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -662,6 +1183,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/ip_messaging/v1/service/__init__.py b/twilio/rest/ip_messaging/v1/service/__init__.py index 3a77cf765e..61c06df216 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -129,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -147,6 +167,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -495,127 +533,7 @@ async def update_async( limits_user_channels=limits_user_channels, ) - @property - def channels(self) -> ChannelList: - """ - Access the channels - """ - return self._proxy.channels - - @property - def roles(self) -> RoleList: - """ - Access the roles - """ - return self._proxy.roles - - @property - def users(self) -> UserList: - """ - Access the users - """ - return self._proxy.users - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ServiceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the ServiceContext - - :param version: Version that contains the resource - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Services/{sid}".format(**self._solution) - - self._channels: Optional[ChannelList] = None - self._roles: Optional[RoleList] = None - self._users: Optional[UserList] = None - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ServiceInstance: - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -671,9 +589,9 @@ def update( webhooks_on_member_removed_method: Union[str, object] = values.unset, limits_channel_members: Union[int, object] = values.unset, limits_user_channels: Union[int, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Update the ServiceInstance + Update the ServiceInstance with HTTP info :param friendly_name: :param default_service_role_sid: @@ -730,69 +648,1066 @@ def update( :param limits_channel_members: :param limits_user_channels: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, @@ -807,12 +1722,10 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, friendly_name: Union[str, object] = values.unset, @@ -930,86 +1843,239 @@ async def update_async( :returns: The updated ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, - "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, - "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, - "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, - "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, ) - headers = values.of({}) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata - headers["Accept"] = "application/json" + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def channels(self) -> ChannelList: @@ -1065,6 +2131,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -1089,13 +2156,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1109,19 +2175,39 @@ def create(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return ServiceInstance(self._version, payload) - async def create_async(self, friendly_name: str) -> ServiceInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance and return response metadata :param friendly_name: - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1135,12 +2221,35 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ServiceInstance(self._version, payload) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -1191,6 +2300,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -1210,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1236,6 +2396,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1244,6 +2405,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1310,6 +2521,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/ip_messaging/v1/service/channel/__init__.py b/twilio/rest/ip_messaging/v1/service/channel/__init__.py index 14423c9e38..bca3bc717b 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -180,6 +218,48 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + @property def invites(self) -> InviteList: """ @@ -234,6 +314,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._members: Optional[MemberList] = None self._messages: Optional[MessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -241,10 +335,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -253,27 +369,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() return ChannelInstance( self._version, payload, @@ -281,22 +413,46 @@ def fetch(self) -> ChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelInstance + Fetch the ChannelInstance and return response metadata - :returns: The fetched ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() return ChannelInstance( self._version, payload, @@ -304,20 +460,33 @@ async def fetch_async(self) -> ChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Update the ChannelInstance + Internal helper for update operation - :param friendly_name: - :param unique_name: - :param attributes: - - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -333,10 +502,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, @@ -344,20 +531,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ChannelInstance + Update the ChannelInstance and return response metadata :param friendly_name: :param unique_name: :param attributes: - :returns: The updated ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -373,10 +583,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) return ChannelInstance( self._version, payload, @@ -384,6 +612,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, unique_name=unique_name, attributes=attributes + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def invites(self) -> InviteList: """ @@ -441,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -472,22 +727,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param friendly_name: - :param unique_name: - :param attributes: - :param type: - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -504,30 +755,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param friendly_name: :param unique_name: :param attributes: :param type: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -544,14 +842,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -606,6 +955,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -627,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -656,6 +1062,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -665,6 +1072,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -699,7 +1162,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -735,7 +1198,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChannelPage: """ @@ -747,7 +1286,7 @@ def get_page(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelPage: """ @@ -759,7 +1298,7 @@ async def get_page_async(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/channel/invite.py b/twilio/rest/ip_messaging/v1/service/channel/invite.py index d348540346..f0b7e70c47 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,10 +215,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -175,27 +249,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InviteInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InviteInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InviteInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() return InviteInstance( self._version, payload, @@ -204,22 +294,47 @@ def fetch(self) -> InviteInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InviteInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InviteInstance + Fetch the InviteInstance and return response metadata - :returns: The fetched InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() return InviteInstance( self._version, payload, @@ -228,6 +343,23 @@ async def fetch_async(self) -> InviteInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -284,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance + Internal helper for create operation - :param identity: - :param role_sid: - - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +439,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -319,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: :param role_sid: - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,10 +506,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -354,6 +529,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata + + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -408,6 +605,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -429,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -458,6 +712,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -467,6 +722,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -501,7 +812,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -537,7 +848,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InvitePage: """ @@ -549,7 +936,7 @@ def get_page(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InvitePage: """ @@ -561,7 +948,7 @@ async def get_page_async(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) def get(self, sid: str) -> InviteContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/channel/member.py b/twilio/rest/ip_messaging/v1/service/channel/member.py index 26a68650ef..6dccde7822 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -163,6 +201,42 @@ async def update_async( last_consumed_message_index=last_consumed_message_index, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +272,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MemberInstance @@ -205,10 +293,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -217,27 +327,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MemberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MemberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MemberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() return MemberInstance( self._version, payload, @@ -246,22 +372,47 @@ def fetch(self) -> MemberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MemberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MemberInstance + Fetch the MemberInstance and return response metadata - :returns: The fetched MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -270,18 +421,33 @@ async def fetch_async(self) -> MemberInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, role_sid: Union[str, object] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Update the MemberInstance - - :param role_sid: - :param last_consumed_message_index: + Internal helper for update operation - :returns: The updated MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,10 +462,26 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + payload, _, _ = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) return MemberInstance( self._version, payload, @@ -308,18 +490,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, role_sid: Union[str, object] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MemberInstance + Update the MemberInstance and return response metadata :param role_sid: :param last_consumed_message_index: - :returns: The updated MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -334,10 +539,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) return MemberInstance( self._version, payload, @@ -346,6 +567,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, last_consumed_message_index=last_consumed_message_index + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -364,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -402,16 +649,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :param identity: - :param role_sid: + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -426,10 +671,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return MemberInstance( self._version, payload, @@ -437,16 +694,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: :param role_sid: - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -461,10 +738,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return MemberInstance( self._version, payload, @@ -472,6 +761,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -526,6 +837,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -547,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -576,6 +944,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -585,6 +954,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -619,7 +1044,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -655,7 +1080,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MemberPage: """ @@ -667,7 +1168,7 @@ def get_page(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MemberPage: """ @@ -679,7 +1180,7 @@ async def get_page_async(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MemberContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/channel/message.py b/twilio/rest/ip_messaging/v1/service/channel/message.py index ad7c05d8a1..6d0ba2da88 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -168,6 +206,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +277,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -210,10 +298,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -222,27 +332,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -251,22 +377,47 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -275,18 +426,33 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, body: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance + Internal helper for update operation - :param body: - :param attributes: - - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -301,10 +467,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + payload, _, _ = self._update(body=body, attributes=attributes) return MessageInstance( self._version, payload, @@ -313,18 +493,39 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, body: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance and return response metadata :param body: :param attributes: - :returns: The updated MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body, attributes=attributes) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -339,10 +540,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async(body=body, attributes=attributes) return MessageInstance( self._version, payload, @@ -351,6 +566,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + body=body, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -369,6 +609,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -407,20 +648,17 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param body: - :param from_: - :param attributes: - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -436,10 +674,26 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + payload, _, _ = self._create(body=body, from_=from_, attributes=attributes) return MessageInstance( self._version, payload, @@ -447,20 +701,43 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param body: :param from_: :param attributes: - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -476,10 +753,28 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + body=body, from_=from_, attributes=attributes + ) return MessageInstance( self._version, payload, @@ -487,6 +782,32 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param body: + :param from_: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -541,6 +862,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -562,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -591,6 +969,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -600,6 +979,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -634,7 +1069,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -670,7 +1105,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -682,7 +1193,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -694,7 +1205,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/role.py b/twilio/rest/ip_messaging/v1/service/role.py index d5d0628032..e7156129ef 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,10 +257,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -193,27 +291,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, @@ -221,22 +335,46 @@ def fetch(self) -> RoleInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -244,13 +382,28 @@ async def fetch_async(self) -> RoleInstance: sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +417,19 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -275,13 +437,29 @@ def update(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +473,19 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance( self._version, payload, @@ -306,6 +493,23 @@ async def update_async(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -324,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -355,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: - :param type: - :param permission: - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,25 +583,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: :param type: :param permission: - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +649,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -492,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -526,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -557,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -590,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RolePage: """ @@ -602,7 +1043,7 @@ def get_page(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RolePage: """ @@ -614,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/user/__init__.py b/twilio/rest/ip_messaging/v1/service/user/__init__.py index 5f37f2d3aa..a428c09856 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -171,6 +209,48 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_channels(self) -> UserChannelList: """ @@ -209,6 +289,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -216,10 +310,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -228,27 +344,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, @@ -256,22 +388,46 @@ def fetch(self) -> UserInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -279,20 +435,33 @@ async def fetch_async(self) -> UserInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance + Internal helper for update operation - :param role_sid: - :param attributes: - :param friendly_name: - - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +477,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + payload, _, _ = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) return UserInstance( self._version, payload, @@ -319,20 +506,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance and return response metadata :param role_sid: :param attributes: :param friendly_name: - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -348,10 +558,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) return UserInstance( self._version, payload, @@ -359,6 +587,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + role_sid=role_sid, attributes=attributes, friendly_name=friendly_name + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def user_channels(self) -> UserChannelList: """ @@ -390,6 +644,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -421,22 +676,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: - :param role_sid: - :param attributes: - :param friendly_name: - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -453,30 +704,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: :param role_sid: :param attributes: :param friendly_name: - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,14 +791,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -551,6 +900,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -570,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,6 +996,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -604,6 +1005,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -635,7 +1086,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -668,7 +1119,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -680,7 +1201,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -692,7 +1213,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserContext: """ diff --git a/twilio/rest/ip_messaging/v1/service/user/user_channel.py b/twilio/rest/ip_messaging/v1/service/user/user_channel.py index 4245449869..28ee7b4930 100644 --- a/twilio/rest/ip_messaging/v1/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -170,6 +172,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -189,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -215,6 +268,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +277,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -254,7 +358,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -287,7 +391,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserChannelPage: """ @@ -299,7 +473,7 @@ def get_page(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserChannelPage: """ @@ -311,7 +485,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/ip_messaging/v2/credential.py b/twilio/rest/ip_messaging/v2/credential.py index 065c5048e9..7032a6e2f3 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,56 +354,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -277,18 +465,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -307,13 +489,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -323,7 +503,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param friendly_name: :param certificate: @@ -334,6 +514,63 @@ async def update_async( :returns: The updated CredentialInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +588,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -375,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -399,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -408,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance - - :param type: - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -440,13 +732,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -457,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: @@ -469,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -487,12 +839,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -543,6 +962,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -562,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -588,6 +1058,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -596,6 +1067,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -662,6 +1183,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/ip_messaging/v2/service/__init__.py b/twilio/rest/ip_messaging/v2/service/__init__.py index a303f10f33..a00dfed962 100644 --- a/twilio/rest/ip_messaging/v2/service/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -103,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -370,135 +408,7 @@ async def update_async( notifications_log_enabled=notifications_log_enabled, ) - @property - def bindings(self) -> BindingList: - """ - Access the bindings - """ - return self._proxy.bindings - - @property - def channels(self) -> ChannelList: - """ - Access the channels - """ - return self._proxy.channels - - @property - def roles(self) -> RoleList: - """ - Access the roles - """ - return self._proxy.roles - - @property - def users(self) -> UserList: - """ - Access the users - """ - return self._proxy.users - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class ServiceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the ServiceContext - - :param version: Version that contains the resource - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Services/{sid}".format(**self._solution) - - self._bindings: Optional[BindingList] = None - self._channels: Optional[ChannelList] = None - self._roles: Optional[RoleList] = None - self._users: Optional[UserList] = None - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ServiceInstance: - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -533,9 +443,9 @@ def update( pre_webhook_retry_count: Union[int, object] = values.unset, post_webhook_retry_count: Union[int, object] = values.unset, notifications_log_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Update the ServiceInstance + Update the ServiceInstance with HTTP info :param friendly_name: :param default_service_role_sid: @@ -569,71 +479,43 @@ def update( :param post_webhook_retry_count: :param notifications_log_enabled: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( - notifications_new_message_badge_count_enabled - ), - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - "Media.CompatibilityMessage": media_compatibility_message, - "PreWebhookRetryCount": pre_webhook_retry_count, - "PostWebhookRetryCount": post_webhook_retry_count, - "Notifications.LogEnabled": serialize.boolean_to_string( - notifications_log_enabled - ), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + async def update_with_http_info_async( self, friendly_name: Union[str, object] = values.unset, default_service_role_sid: Union[str, object] = values.unset, @@ -668,9 +550,9 @@ async def update_async( pre_webhook_retry_count: Union[int, object] = values.unset, post_webhook_retry_count: Union[int, object] = values.unset, notifications_log_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ServiceInstance + Asynchronous coroutine to update the ServiceInstance with HTTP info :param friendly_name: :param default_service_role_sid: @@ -704,21 +586,634 @@ async def update_async( :param post_webhook_retry_count: :param notifications_log_enabled: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, "Notifications.NewMessage.Enabled": serialize.boolean_to_string( notifications_new_message_enabled ), @@ -760,13 +1255,228 @@ async def update_async( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def bindings(self) -> BindingList: @@ -834,6 +1544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -858,13 +1569,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -878,19 +1588,39 @@ def create(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return ServiceInstance(self._version, payload) - async def create_async(self, friendly_name: str) -> ServiceInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance and return response metadata :param friendly_name: - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -904,12 +1634,35 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ServiceInstance(self._version, payload) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -960,6 +1713,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -979,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1005,6 +1809,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1013,6 +1818,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1079,6 +1934,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/ip_messaging/v2/service/binding.py b/twilio/rest/ip_messaging/v2/service/binding.py index af9018af9f..b7394ff7a1 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +197,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,10 +218,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -178,27 +252,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = self._fetch() return BindingInstance( self._version, payload, @@ -206,22 +296,46 @@ def fetch(self) -> BindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> BindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BindingInstance + Fetch the BindingInstance and return response metadata - :returns: The fetched BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() return BindingInstance( self._version, payload, @@ -229,6 +343,22 @@ async def fetch_async(self) -> BindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,6 +377,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -340,6 +471,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -363,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -395,6 +587,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -405,6 +598,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, @@ -442,7 +697,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -481,7 +736,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BindingPage: """ @@ -493,7 +830,7 @@ def get_page(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BindingPage: """ @@ -505,7 +842,7 @@ async def get_page_async(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> BindingContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/channel/__init__.py b/twilio/rest/ip_messaging/v2/service/channel/__init__.py index 8220a4be9c..5dd5288a73 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -141,6 +143,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -159,6 +195,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -229,6 +283,76 @@ async def update_async( created_by=created_by, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + @property def invites(self) -> InviteList: """ @@ -291,6 +415,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._messages: Optional[MessageList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -304,6 +452,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -312,7 +493,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -327,32 +510,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> ChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + :returns: The fetched ChannelInstance + """ + payload, _, _ = self._fetch() return ChannelInstance( self._version, payload, @@ -360,22 +564,46 @@ def fetch(self) -> ChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelInstance + Fetch the ChannelInstance and return response metadata - :returns: The fetched ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + payload, _, _ = await self._fetch_async() return ChannelInstance( self._version, payload, @@ -383,7 +611,23 @@ async def fetch_async(self) -> ChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -394,19 +638,12 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Update the ChannelInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: - :param unique_name: - :param attributes: - :param date_created: - :param date_updated: - :param created_by: + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -434,18 +671,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ChannelInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -458,7 +688,7 @@ async def update_async( created_by: Union[str, object] = values.unset, ) -> ChannelInstance: """ - Asynchronous coroutine to update the ChannelInstance + Update the ChannelInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: @@ -470,36 +700,15 @@ async def update_async( :returns: The updated ChannelInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "CreatedBy": created_by, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, ) - return ChannelInstance( self._version, payload, @@ -507,14 +716,187 @@ async def update_async( sid=self._solution["sid"], ) - @property - def invites(self) -> InviteList: - """ - Access the invites - """ - if self._invites is None: - self._invites = InviteList( - self._version, + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, self._solution["service_sid"], self._solution["sid"], ) @@ -577,6 +959,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -608,7 +991,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -620,20 +1003,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: - :param unique_name: - :param attributes: - :param type: - :param date_created: - :param date_updated: - :param created_by: - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -658,15 +1033,52 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -678,9 +1090,9 @@ async def create_async( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: @@ -691,7 +1103,41 @@ async def create_async( :param date_updated: :param created_by: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -716,14 +1162,93 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -778,6 +1303,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + type=type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -799,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -828,6 +1410,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -837,6 +1420,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelInstance and returns headers from first page + + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -871,7 +1510,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -907,7 +1546,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelPage, status code, and headers + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChannelPage: """ @@ -919,7 +1634,7 @@ def get_page(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelPage: """ @@ -931,7 +1646,7 @@ async def get_page_async(self, target_url: str) -> ChannelPage: :returns: Page of ChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelPage(self._version, response, self._solution) + return ChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/channel/invite.py b/twilio/rest/ip_messaging/v2/service/channel/invite.py index 4fa3c187fc..3faf373020 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,10 +215,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -175,27 +249,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InviteInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InviteInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InviteInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + :returns: The fetched InviteInstance + """ + payload, _, _ = self._fetch() return InviteInstance( self._version, payload, @@ -204,22 +294,47 @@ def fetch(self) -> InviteInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InviteInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InviteInstance + Fetch the InviteInstance and return response metadata - :returns: The fetched InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + payload, _, _ = await self._fetch_async() return InviteInstance( self._version, payload, @@ -228,6 +343,23 @@ async def fetch_async(self) -> InviteInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -284,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance + Internal helper for create operation - :param identity: - :param role_sid: - - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +439,22 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = self._create(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -319,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: :param role_sid: - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,10 +506,22 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + payload, _, _ = await self._create_async(identity=identity, role_sid=role_sid) return InviteInstance( self._version, payload, @@ -354,6 +529,28 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InviteInstance and return response metadata + + :param identity: + :param role_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -408,6 +605,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -429,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -458,6 +712,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -467,6 +722,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InviteInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -501,7 +812,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -537,7 +848,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InvitePage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InvitePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InvitePage: """ @@ -549,7 +936,7 @@ def get_page(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InvitePage: """ @@ -561,7 +948,7 @@ async def get_page_async(self, target_url: str) -> InvitePage: :returns: Page of InviteInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InvitePage(self._version, response, self._solution) + return InvitePage(self._version, response, solution=self._solution) def get(self, sid: str) -> InviteContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/channel/member.py b/twilio/rest/ip_messaging/v2/service/channel/member.py index 6456d3be20..580bbbe1a4 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -132,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -150,6 +186,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -220,6 +274,76 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -255,6 +379,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -268,6 +416,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -276,7 +457,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -291,32 +474,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MemberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MemberInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MemberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + :returns: The fetched MemberInstance + """ + payload, _, _ = self._fetch() return MemberInstance( self._version, payload, @@ -325,22 +529,47 @@ def fetch(self) -> MemberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MemberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MemberInstance + Fetch the MemberInstance and return response metadata - :returns: The fetched MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -349,7 +578,24 @@ async def fetch_async(self) -> MemberInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -360,19 +606,12 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Update the MemberInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: - :param last_consumed_message_index: - :param last_consumption_timestamp: - :param date_created: - :param date_updated: - :param attributes: + Internal helper for update operation - :returns: The updated MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -402,19 +641,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MemberInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -427,7 +658,7 @@ async def update_async( attributes: Union[str, object] = values.unset, ) -> MemberInstance: """ - Asynchronous coroutine to update the MemberInstance + Update the MemberInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param role_sid: @@ -439,38 +670,15 @@ async def update_async( :returns: The updated MemberInstance """ - - data = values.of( - { - "RoleSid": role_sid, - "LastConsumedMessageIndex": last_consumed_message_index, - "LastConsumptionTimestamp": serialize.iso8601_datetime( - last_consumption_timestamp - ), - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, ) - return MemberInstance( self._version, payload, @@ -479,9 +687,187 @@ async def update_async( sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation :returns: Machine friendly representation """ @@ -497,6 +883,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -535,7 +922,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -547,20 +934,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance + Internal helper for create operation - :param identity: - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: - :param last_consumed_message_index: - :param last_consumption_timestamp: - :param date_created: - :param date_updated: - :param attributes: - - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -587,10 +966,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) return MemberInstance( self._version, payload, @@ -598,7 +1014,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -610,9 +1026,9 @@ async def create_async( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -623,7 +1039,44 @@ async def create_async( :param date_updated: :param attributes: - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -650,10 +1103,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) return MemberInstance( self._version, payload, @@ -661,6 +1151,51 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MemberInstance and return response metadata + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[List[str], object] = values.unset, @@ -715,6 +1250,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[List[str], object] = values.unset, @@ -736,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -765,6 +1357,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -774,6 +1367,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MemberInstance and returns headers from first page + + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[List[str], object] = values.unset, @@ -808,7 +1457,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -844,7 +1493,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MemberPage, status code, and headers + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MemberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MemberPage: """ @@ -856,7 +1581,7 @@ def get_page(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MemberPage: """ @@ -868,7 +1593,7 @@ async def get_page_async(self, target_url: str) -> MemberPage: :returns: Page of MemberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MemberPage(self._version, response, self._solution) + return MemberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MemberContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/channel/message.py b/twilio/rest/ip_messaging/v2/service/channel/message.py index 838b3c7271..f53ed8a70b 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -140,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -158,6 +194,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -228,6 +282,76 @@ async def update_async( from_=from_, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -263,6 +387,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -276,6 +424,39 @@ def delete( :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(x_twilio_webhook_enabled=x_twilio_webhook_enabled) + return success + + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, @@ -284,7 +465,9 @@ def delete( headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async( self, @@ -299,32 +482,53 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } + success, _, _ = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled ) + return success - headers = values.of({}) + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - def fetch(self) -> MessageInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessageInstance + success, status_code, headers = await self._delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessageInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + :returns: The fetched MessageInstance + """ + payload, _, _ = self._fetch() return MessageInstance( self._version, payload, @@ -333,22 +537,47 @@ def fetch(self) -> MessageInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInstance + Fetch the MessageInstance and return response metadata - :returns: The fetched MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + payload, _, _ = await self._fetch_async() return MessageInstance( self._version, payload, @@ -357,7 +586,24 @@ async def fetch_async(self) -> MessageInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -368,19 +614,12 @@ def update( date_updated: Union[datetime, object] = values.unset, last_updated_by: Union[str, object] = values.unset, from_: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param body: - :param attributes: - :param date_created: - :param date_updated: - :param last_updated_by: - :param from_: + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,19 +647,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return MessageInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) - - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -433,7 +664,7 @@ async def update_async( from_: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param body: @@ -445,36 +676,15 @@ async def update_async( :returns: The updated MessageInstance """ - - data = values.of( - { - "Body": body, - "Attributes": attributes, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "LastUpdatedBy": last_updated_by, - "From": from_, - } - ) - headers = values.of({}) - - if not ( - x_twilio_webhook_enabled is values.unset - or ( - isinstance(x_twilio_webhook_enabled, str) - and not x_twilio_webhook_enabled - ) - ): - headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, ) - return MessageInstance( self._version, payload, @@ -483,11 +693,187 @@ async def update_async( sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -501,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -539,7 +926,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -551,20 +938,12 @@ def create( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param from_: - :param attributes: - :param date_created: - :param date_updated: - :param last_updated_by: - :param body: - :param media_sid: - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -589,10 +968,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) return MessageInstance( self._version, payload, @@ -600,7 +1016,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -612,9 +1028,9 @@ async def create_async( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param from_: @@ -625,7 +1041,44 @@ async def create_async( :param body: :param media_sid: - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -650,10 +1103,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) return MessageInstance( self._version, payload, @@ -661,6 +1151,51 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -715,6 +1250,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -736,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -765,6 +1357,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -774,6 +1367,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInstance and returns headers from first page + + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["MessageInstance.OrderType", object] = values.unset, @@ -808,7 +1457,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def page_async( self, @@ -844,7 +1493,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagePage, status code, and headers + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagePage: """ @@ -856,7 +1581,7 @@ def get_page(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessagePage: """ @@ -868,7 +1593,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/channel/webhook.py b/twilio/rest/ip_messaging/v2/service/channel/webhook.py index 3c7570fd0e..a72375bb7a 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/webhook.py +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -189,6 +227,66 @@ async def update_async( configuration_retry_count=configuration_retry_count, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,6 +322,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -231,10 +343,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -243,27 +377,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebhookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebhookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, @@ -272,22 +422,47 @@ def fetch(self) -> WebhookInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, @@ -296,7 +471,24 @@ async def fetch_async(self) -> WebhookInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -304,18 +496,12 @@ def update( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Update the WebhookInstance + Internal helper for update operation - :param configuration_url: - :param configuration_method: - :param configuration_filters: - :param configuration_triggers: - :param configuration_flow_sid: - :param configuration_retry_count: - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -338,10 +524,39 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -350,7 +565,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -358,9 +573,9 @@ async def update_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param configuration_url: :param configuration_method: @@ -369,7 +584,39 @@ async def update_async( :param configuration_flow_sid: :param configuration_retry_count: - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -392,10 +639,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -404,6 +680,44 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -422,6 +736,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, @@ -460,7 +775,7 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, type: "WebhookInstance.Type", configuration_url: Union[str, object] = values.unset, @@ -469,19 +784,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param type: - :param configuration_url: - :param configuration_method: - :param configuration_filters: - :param configuration_triggers: - :param configuration_flow_sid: - :param configuration_retry_count: + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -505,10 +813,42 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -516,7 +856,7 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, type: "WebhookInstance.Type", configuration_url: Union[str, object] = values.unset, @@ -525,9 +865,9 @@ async def create_async( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param type: :param configuration_url: @@ -537,7 +877,40 @@ async def create_async( :param configuration_flow_sid: :param configuration_retry_count: - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -561,10 +934,42 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) return WebhookInstance( self._version, payload, @@ -572,6 +977,46 @@ async def create_async( channel_sid=self._solution["channel_sid"], ) + async def create_with_http_info_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -622,6 +1067,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -641,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -667,6 +1163,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -675,6 +1172,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -706,7 +1253,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -739,7 +1286,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WebhookPage: """ @@ -751,7 +1368,7 @@ def get_page(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WebhookPage: """ @@ -763,7 +1380,7 @@ async def get_page_async(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WebhookContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/role.py b/twilio/rest/ip_messaging/v2/service/role.py index 32f70c2272..02f3e055e0 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,10 +257,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -193,27 +291,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + :returns: The fetched RoleInstance + """ + payload, _, _ = self._fetch() return RoleInstance( self._version, payload, @@ -221,22 +335,46 @@ def fetch(self) -> RoleInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoleInstance + Fetch the RoleInstance and return response metadata - :returns: The fetched RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -244,13 +382,28 @@ async def fetch_async(self) -> RoleInstance: sid=self._solution["sid"], ) - def update(self, permission: List[str]) -> RoleInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoleInstance + Asynchronous coroutine to fetch the RoleInstance and return response metadata - :param permission: - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, permission: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +417,19 @@ def update(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -275,13 +437,29 @@ def update(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) - async def update_async(self, permission: List[str]) -> RoleInstance: + def update_with_http_info(self, permission: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the RoleInstance + Update the RoleInstance and return response metadata :param permission: - :returns: The updated RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, permission: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -295,10 +473,19 @@ async def update_async(self, permission: List[str]) -> RoleInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = await self._update_async(permission=permission) return RoleInstance( self._version, payload, @@ -306,6 +493,23 @@ async def update_async(self, permission: List[str]) -> RoleInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance and return response metadata + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(permission=permission) + instance = RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -324,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -355,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: - :param type: - :param permission: - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,25 +583,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: :param type: :param permission: - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +649,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,6 +742,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -492,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,6 +838,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -526,6 +847,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -557,7 +928,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -590,7 +961,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RolePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RolePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RolePage: """ @@ -602,7 +1043,7 @@ def get_page(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RolePage: """ @@ -614,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> RolePage: :returns: Page of RoleInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RolePage(self._version, response, self._solution) + return RolePage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/user/__init__.py b/twilio/rest/ip_messaging/v2/service/user/__init__.py index f5f1454c72..b6eb03d7f4 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -117,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -135,6 +155,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -187,6 +225,58 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_bindings(self) -> UserBindingList: """ @@ -233,6 +323,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_bindings: Optional[UserBindingList] = None self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -240,10 +344,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -252,27 +378,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + :returns: The fetched UserInstance + """ + payload, _, _ = self._fetch() return UserInstance( self._version, payload, @@ -280,22 +422,46 @@ def fetch(self) -> UserInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserInstance + Fetch the UserInstance and return response metadata - :returns: The fetched UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -303,7 +469,23 @@ async def fetch_async(self) -> UserInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -311,16 +493,12 @@ def update( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Update the UserInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: - :param attributes: - :param friendly_name: + Internal helper for update operation - :returns: The updated UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -345,10 +523,35 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, @@ -356,7 +559,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -364,16 +567,45 @@ async def update_async( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Update the UserInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param role_sid: :param attributes: :param friendly_name: - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -398,10 +630,35 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, @@ -409,6 +666,39 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def user_bindings(self) -> UserBindingList: """ @@ -453,6 +743,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -484,7 +775,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -493,17 +784,12 @@ def create( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: - :param attributes: - :param friendly_name: - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -525,15 +811,43 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -542,9 +856,9 @@ async def create_async( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header @@ -552,7 +866,35 @@ async def create_async( :param attributes: :param friendly_name: - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -574,14 +916,75 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -632,6 +1035,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -651,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -677,6 +1131,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -685,6 +1140,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -716,7 +1221,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -749,7 +1254,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -761,7 +1336,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -773,7 +1348,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/user/user_binding.py b/twilio/rest/ip_messaging/v2/service/user/user_binding.py index 4f1d9f10a7..cf7b3f7fc9 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_binding.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "user_sid": user_sid, "sid": sid or self.sid, } + self._context: Optional[UserBindingContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserBindingInstance": """ Fetch the UserBindingInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "UserBindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserBindingInstance @@ -173,10 +225,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -185,27 +259,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserBindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserBindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserBindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + payload, _, _ = self._fetch() return UserBindingInstance( self._version, payload, @@ -214,22 +304,47 @@ def fetch(self) -> UserBindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UserBindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserBindingInstance + Fetch the UserBindingInstance and return response metadata - :returns: The fetched UserBindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + payload, _, _ = await self._fetch_async() return UserBindingInstance( self._version, payload, @@ -238,6 +353,23 @@ async def fetch_async(self) -> UserBindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -256,6 +388,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -354,6 +487,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, binding_type: Union[ @@ -377,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -408,6 +602,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -417,6 +612,66 @@ async def list_async( ) ] + def list_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserBindingInstance and returns headers from first page + + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, binding_type: Union[ @@ -453,7 +708,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -491,7 +746,87 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserBindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserBindingPage, status code, and headers + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserBindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserBindingPage: """ @@ -503,7 +838,7 @@ def get_page(self, target_url: str) -> UserBindingPage: :returns: Page of UserBindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserBindingPage: """ @@ -515,7 +850,7 @@ async def get_page_async(self, target_url: str) -> UserBindingPage: :returns: Page of UserBindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserBindingPage(self._version, response, self._solution) + return UserBindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UserBindingContext: """ diff --git a/twilio/rest/ip_messaging/v2/service/user/user_channel.py b/twilio/rest/ip_messaging/v2/service/user/user_channel.py index 5cb544fc3f..db12f64be8 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "user_sid": user_sid, "channel_sid": channel_sid or self.channel_sid, } + self._context: Optional[UserChannelContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserChannelInstance": """ Fetch the UserChannelInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "UserChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -183,6 +221,52 @@ async def update_async( last_consumption_timestamp=last_consumption_timestamp, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -220,6 +304,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserChannelInstance @@ -227,10 +325,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -239,27 +359,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UserChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UserChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = self._fetch() return UserChannelInstance( self._version, payload, @@ -268,22 +404,47 @@ def fetch(self) -> UserChannelInstance: channel_sid=self._solution["channel_sid"], ) - async def fetch_async(self) -> UserChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the UserChannelInstance + Fetch the UserChannelInstance and return response metadata - :returns: The fetched UserChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + payload, _, _ = await self._fetch_async() return UserChannelInstance( self._version, payload, @@ -292,22 +453,36 @@ async def fetch_async(self) -> UserChannelInstance: channel_sid=self._solution["channel_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, notification_level: Union[ "UserChannelInstance.NotificationLevel", object ] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, last_consumption_timestamp: Union[datetime, object] = values.unset, - ) -> UserChannelInstance: + ) -> tuple: """ - Update the UserChannelInstance + Internal helper for update operation - :param notification_level: - :param last_consumed_message_index: - :param last_consumption_timestamp: - - :returns: The updated UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -325,10 +500,32 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + payload, _, _ = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) return UserChannelInstance( self._version, payload, @@ -337,22 +534,50 @@ def update( channel_sid=self._solution["channel_sid"], ) - async def update_async( + def update_with_http_info( self, notification_level: Union[ "UserChannelInstance.NotificationLevel", object ] = values.unset, last_consumed_message_index: Union[int, object] = values.unset, last_consumption_timestamp: Union[datetime, object] = values.unset, - ) -> UserChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserChannelInstance + Update the UserChannelInstance and return response metadata :param notification_level: :param last_consumed_message_index: :param last_consumption_timestamp: - :returns: The updated UserChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -370,10 +595,32 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + payload, _, _ = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) return UserChannelInstance( self._version, payload, @@ -382,6 +629,37 @@ async def update_async( channel_sid=self._solution["channel_sid"], ) + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance and return response metadata + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + instance = UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -400,6 +678,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -488,6 +767,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -507,6 +836,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -533,6 +863,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -541,6 +872,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -572,7 +953,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -605,7 +986,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserChannelPage: """ @@ -617,7 +1068,7 @@ def get_page(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserChannelPage: """ @@ -629,7 +1080,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def get(self, channel_sid: str) -> UserChannelContext: """ diff --git a/twilio/rest/microvisor/MicrovisorBase.py b/twilio/rest/knowledge/KnowledgeBase.py similarity index 62% rename from twilio/rest/microvisor/MicrovisorBase.py rename to twilio/rest/knowledge/KnowledgeBase.py index e8c874b920..c92fd50540 100644 --- a/twilio/rest/microvisor/MicrovisorBase.py +++ b/twilio/rest/knowledge/KnowledgeBase.py @@ -13,32 +13,43 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.microvisor.v1 import V1 +from twilio.rest.knowledge.v1 import V1 +from twilio.rest.knowledge.v2 import V2 -class MicrovisorBase(Domain): +class KnowledgeBase(Domain): def __init__(self, twilio: Client): """ - Initialize the Microvisor Domain + Initialize the Knowledge Domain - :returns: Domain for Microvisor + :returns: Domain for Knowledge """ - super().__init__(twilio, "https://microvisor.twilio.com") + super().__init__(twilio, "https://knowledge.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: """ - :returns: Versions v1 of Microvisor + :returns: Versions v1 of Knowledge """ if self._v1 is None: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Knowledge + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/knowledge/__init__.py b/twilio/rest/knowledge/__init__.py new file mode 100644 index 0000000000..ed6256683a --- /dev/null +++ b/twilio/rest/knowledge/__init__.py @@ -0,0 +1,5 @@ +from twilio.rest.knowledge.KnowledgeBase import KnowledgeBase + + +class Knowledge(KnowledgeBase): + pass diff --git a/twilio/rest/preview/sync/__init__.py b/twilio/rest/knowledge/v1/__init__.py similarity index 62% rename from twilio/rest/preview/sync/__init__.py rename to twilio/rest/knowledge/v1/__init__.py index d84c79039b..9609bff951 100644 --- a/twilio/rest/preview/sync/__init__.py +++ b/twilio/rest/knowledge/v1/__init__.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Preview + Twilio - Knowledge This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,29 +15,29 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.preview.sync.service import ServiceList +from twilio.rest.knowledge.v1.knowledge import KnowledgeList -class Sync(Version): +class V1(Version): def __init__(self, domain: Domain): """ - Initialize the Sync version of Preview + Initialize the V1 version of Knowledge - :param domain: The Twilio.preview domain + :param domain: The Twilio.knowledge domain """ - super().__init__(domain, "Sync") - self._services: Optional[ServiceList] = None + super().__init__(domain, "v1") + self._knowledge: Optional[KnowledgeList] = None @property - def services(self) -> ServiceList: - if self._services is None: - self._services = ServiceList(self) - return self._services + def knowledge(self) -> KnowledgeList: + if self._knowledge is None: + self._knowledge = KnowledgeList(self) + return self._knowledge def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/assistants/v1/knowledge/__init__.py b/twilio/rest/knowledge/v1/knowledge/__init__.py similarity index 57% rename from twilio/rest/assistants/v1/knowledge/__init__.py rename to twilio/rest/knowledge/v1/knowledge/__init__.py index 7d616f8682..55395f0737 100644 --- a/twilio/rest/assistants/v1/knowledge/__init__.py +++ b/twilio/rest/knowledge/v1/knowledge/__init__.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Assistants + Twilio - Knowledge This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,20 +15,20 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version from twilio.base.page import Page -from twilio.rest.assistants.v1.knowledge.chunk import ChunkList -from twilio.rest.assistants.v1.knowledge.knowledge_status import KnowledgeStatusList +from twilio.rest.knowledge.v1.knowledge.chunk import ChunkList +from twilio.rest.knowledge.v1.knowledge.knowledge_status import KnowledgeStatusList class KnowledgeInstance(InstanceResource): - class AssistantsV1ServiceCreateKnowledgeRequest(object): + class KnowledgeV1ServiceCreateKnowledgeRequest(object): """ - :ivar assistant_id: The Assistant ID. :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. :ivar name: The name of the tool. @@ -39,21 +39,19 @@ class AssistantsV1ServiceCreateKnowledgeRequest(object): def __init__(self, payload: Dict[str, Any]): - self.assistant_id: Optional[str] = payload.get("assistant_id") self.description: Optional[str] = payload.get("description") self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( "knowledge_source_details" ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") def to_dict(self): return { - "assistant_id": self.assistant_id, "description": self.description, "knowledge_source_details": self.knowledge_source_details, "name": self.name, @@ -62,7 +60,7 @@ def to_dict(self): "embedding_model": self.embedding_model, } - class AssistantsV1ServiceCreatePolicyRequest(object): + class KnowledgeV1ServiceCreatePolicyRequest(object): """ :ivar description: The description of the policy. :ivar id: The Policy ID. @@ -90,7 +88,7 @@ def to_dict(self): "type": self.type, } - class AssistantsV1ServiceUpdateKnowledgeRequest(object): + class KnowledgeV1ServiceUpdateKnowledgeRequest(object): """ :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. @@ -108,7 +106,7 @@ def __init__(self, payload: Dict[str, Any]): ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") @@ -163,6 +161,7 @@ def __init__( self._solution = { "id": id or self.id, } + self._context: Optional[KnowledgeContext] = None @property @@ -198,6 +197,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "KnowledgeInstance": """ Fetch the KnowledgeInstance @@ -216,38 +233,90 @@ async def fetch_async(self) -> "KnowledgeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, - assistants_v1_service_update_knowledge_request: Union[ - AssistantsV1ServiceUpdateKnowledgeRequest, object + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object ] = values.unset, ) -> "KnowledgeInstance": """ Update the KnowledgeInstance - :param assistants_v1_service_update_knowledge_request: + :param knowledge_v1_service_update_knowledge_request: :returns: The updated KnowledgeInstance """ return self._proxy.update( - assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, ) async def update_async( self, - assistants_v1_service_update_knowledge_request: Union[ - AssistantsV1ServiceUpdateKnowledgeRequest, object + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object ] = values.unset, ) -> "KnowledgeInstance": """ Asynchronous coroutine to update the KnowledgeInstance - :param assistants_v1_service_update_knowledge_request: + :param knowledge_v1_service_update_knowledge_request: :returns: The updated KnowledgeInstance """ return await self._proxy.update_async( - assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + def update_with_http_info( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + async def update_with_http_info_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, ) @property @@ -271,14 +340,13 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + return "".format(context) class KnowledgeContext(InstanceContext): - class AssistantsV1ServiceCreateKnowledgeRequest(object): + class KnowledgeV1ServiceCreateKnowledgeRequest(object): """ - :ivar assistant_id: The Assistant ID. :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. :ivar name: The name of the tool. @@ -289,21 +357,19 @@ class AssistantsV1ServiceCreateKnowledgeRequest(object): def __init__(self, payload: Dict[str, Any]): - self.assistant_id: Optional[str] = payload.get("assistant_id") self.description: Optional[str] = payload.get("description") self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( "knowledge_source_details" ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") def to_dict(self): return { - "assistant_id": self.assistant_id, "description": self.description, "knowledge_source_details": self.knowledge_source_details, "name": self.name, @@ -312,7 +378,7 @@ def to_dict(self): "embedding_model": self.embedding_model, } - class AssistantsV1ServiceCreatePolicyRequest(object): + class KnowledgeV1ServiceCreatePolicyRequest(object): """ :ivar description: The description of the policy. :ivar id: The Policy ID. @@ -340,7 +406,7 @@ def to_dict(self): "type": self.type, } - class AssistantsV1ServiceUpdateKnowledgeRequest(object): + class KnowledgeV1ServiceUpdateKnowledgeRequest(object): """ :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. @@ -358,7 +424,7 @@ def __init__(self, payload: Dict[str, Any]): ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") @@ -391,6 +457,20 @@ def __init__(self, version: Version, id: str): self._chunks: Optional[ChunkList] = None self._knowledge_status: Optional[KnowledgeStatusList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the KnowledgeInstance @@ -398,10 +478,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -410,69 +512,122 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> KnowledgeInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the KnowledgeInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched KnowledgeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = self._fetch() return KnowledgeInstance( self._version, payload, id=self._solution["id"], ) - async def fetch_async(self) -> KnowledgeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the KnowledgeInstance + Fetch the KnowledgeInstance and return response metadata - :returns: The fetched KnowledgeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = await self._fetch_async() return KnowledgeInstance( self._version, payload, id=self._solution["id"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, - assistants_v1_service_update_knowledge_request: Union[ - AssistantsV1ServiceUpdateKnowledgeRequest, object + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object ] = values.unset, - ) -> KnowledgeInstance: + ) -> tuple: """ - Update the KnowledgeInstance + Internal helper for update operation - :param assistants_v1_service_update_knowledge_request: - - :returns: The updated KnowledgeInstance + Returns: + tuple: (payload, status_code, headers) """ - data = assistants_v1_service_update_knowledge_request.to_dict() + data = knowledge_v1_service_update_knowledge_request.to_dict() headers = values.of({}) @@ -480,26 +635,60 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="PUT", uri=self._uri, data=data, headers=headers ) - return KnowledgeInstance(self._version, payload, id=self._solution["id"]) - - async def update_async( + def update( self, - assistants_v1_service_update_knowledge_request: Union[ - AssistantsV1ServiceUpdateKnowledgeRequest, object + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object ] = values.unset, ) -> KnowledgeInstance: """ - Asynchronous coroutine to update the KnowledgeInstance + Update the KnowledgeInstance - :param assistants_v1_service_update_knowledge_request: + :param knowledge_v1_service_update_knowledge_request: :returns: The updated KnowledgeInstance """ - data = assistants_v1_service_update_knowledge_request.to_dict() + payload, _, _ = self._update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_v1_service_update_knowledge_request.to_dict() headers = values.of({}) @@ -507,12 +696,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="PUT", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = await self._update_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + async def update_with_http_info_async( + self, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def chunks(self) -> ChunkList: """ @@ -544,7 +768,7 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + return "".format(context) class KnowledgePage(Page): @@ -555,6 +779,7 @@ def get_instance(self, payload: Dict[str, Any]) -> KnowledgeInstance: :param payload: Payload response from the API """ + return KnowledgeInstance(self._version, payload) def __repr__(self) -> str: @@ -563,14 +788,13 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ - return "" + return "" class KnowledgeList(ListResource): - class AssistantsV1ServiceCreateKnowledgeRequest(object): + class KnowledgeV1ServiceCreateKnowledgeRequest(object): """ - :ivar assistant_id: The Assistant ID. :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. :ivar name: The name of the tool. @@ -581,21 +805,19 @@ class AssistantsV1ServiceCreateKnowledgeRequest(object): def __init__(self, payload: Dict[str, Any]): - self.assistant_id: Optional[str] = payload.get("assistant_id") self.description: Optional[str] = payload.get("description") self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( "knowledge_source_details" ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") def to_dict(self): return { - "assistant_id": self.assistant_id, "description": self.description, "knowledge_source_details": self.knowledge_source_details, "name": self.name, @@ -604,7 +826,7 @@ def to_dict(self): "embedding_model": self.embedding_model, } - class AssistantsV1ServiceCreatePolicyRequest(object): + class KnowledgeV1ServiceCreatePolicyRequest(object): """ :ivar description: The description of the policy. :ivar id: The Policy ID. @@ -632,7 +854,7 @@ def to_dict(self): "type": self.type, } - class AssistantsV1ServiceUpdateKnowledgeRequest(object): + class KnowledgeV1ServiceUpdateKnowledgeRequest(object): """ :ivar description: The description of the knowledge source. :ivar knowledge_source_details: The details of the knowledge source based on the type. @@ -650,7 +872,7 @@ def __init__(self, payload: Dict[str, Any]): ) self.name: Optional[str] = payload.get("name") self.policy: Optional[ - KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + KnowledgeList.KnowledgeV1ServiceCreatePolicyRequest ] = payload.get("policy") self.type: Optional[str] = payload.get("type") self.embedding_model: Optional[str] = payload.get("embedding_model") @@ -676,18 +898,17 @@ def __init__(self, version: Version): self._uri = "/Knowledge" - def create( + def _create( self, - assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, - ) -> KnowledgeInstance: + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> tuple: """ - Create the KnowledgeInstance - - :param assistants_v1_service_create_knowledge_request: + Internal helper for create operation - :returns: The created KnowledgeInstance + Returns: + tuple: (payload, status_code, headers) """ - data = assistants_v1_service_create_knowledge_request.to_dict() + data = knowledge_v1_service_create_knowledge_request.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -695,24 +916,54 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return KnowledgeInstance(self._version, payload) - - async def create_async( + def create( self, - assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, ) -> KnowledgeInstance: """ - Asynchronously create the KnowledgeInstance + Create the KnowledgeInstance - :param assistants_v1_service_create_knowledge_request: + :param knowledge_v1_service_create_knowledge_request: :returns: The created KnowledgeInstance """ - data = assistants_v1_service_create_knowledge_request.to_dict() + payload, _, _ = self._create( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + def create_with_http_info( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_v1_service_create_knowledge_request.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -720,15 +971,46 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param knowledge_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = await self._create_async( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) return KnowledgeInstance(self._version, payload) + async def create_with_http_info_async( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param knowledge_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_v1_service_create_knowledge_request=knowledge_v1_service_create_knowledge_request + ) + instance = KnowledgeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[KnowledgeInstance]: @@ -738,7 +1020,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str assistant_id: + :param str tags: Json array of tag and value pairs for tag filtering. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -749,13 +1031,13 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) + page = self.page(tags=tags, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[KnowledgeInstance]: @@ -765,7 +1047,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str assistant_id: + :param str tags: Json array of tag and value pairs for tag filtering. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -776,15 +1058,69 @@ async def stream_async( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - assistant_id=assistant_id, page_size=limits["page_size"] - ) + page = await self.page_async(tags=tags, page_size=limits["page_size"]) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tags=tags, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tags=tags, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[KnowledgeInstance]: @@ -793,7 +1129,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str assistant_id: + :param str tags: Json array of tag and value pairs for tag filtering. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -803,9 +1139,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - assistant_id=assistant_id, + tags=tags, limit=limit, page_size=page_size, ) @@ -813,7 +1150,7 @@ def list( async def list_async( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[KnowledgeInstance]: @@ -822,7 +1159,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str assistant_id: + :param str tags: Json array of tag and value pairs for tag filtering. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -832,18 +1169,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - assistant_id=assistant_id, + tags=tags, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tags=tags, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeInstance and returns headers from first page + + + :param str tags: Json array of tag and value pairs for tag filtering. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tags=tags, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -852,7 +1246,7 @@ def page( Retrieve a single page of KnowledgeInstance records from the API. Request is executed immediately - :param assistant_id: + :param tags: Json array of tag and value pairs for tag filtering. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -861,7 +1255,7 @@ def page( """ data = values.of( { - "AssistantId": assistant_id, + "Tags": tags, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -879,7 +1273,7 @@ def page( async def page_async( self, - assistant_id: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -888,7 +1282,7 @@ async def page_async( Asynchronously retrieve a single page of KnowledgeInstance records from the API. Request is executed immediately - :param assistant_id: + :param tags: Json array of tag and value pairs for tag filtering. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -897,7 +1291,7 @@ async def page_async( """ data = values.of( { - "AssistantId": assistant_id, + "Tags": tags, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -913,6 +1307,82 @@ async def page_async( ) return KnowledgePage(self._version, response) + def page_with_http_info( + self, + tags: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + tags: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param tags: Json array of tag and value pairs for tag filtering. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "Tags": tags, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> KnowledgePage: """ Retrieve a specific page of KnowledgeInstance records from the API. @@ -959,4 +1429,4 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/assistants/v1/knowledge/chunk.py b/twilio/rest/knowledge/v1/knowledge/chunk.py similarity index 58% rename from twilio/rest/assistants/v1/knowledge/chunk.py rename to twilio/rest/knowledge/v1/knowledge/chunk.py index be90a7626e..97dbe422d6 100644 --- a/twilio/rest/assistants/v1/knowledge/chunk.py +++ b/twilio/rest/knowledge/v1/knowledge/chunk.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Assistants + Twilio - Knowledge This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,7 +56,7 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + return "".format(context) class ChunkPage(Page): @@ -66,6 +67,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChunkInstance: :param payload: Payload response from the API """ + return ChunkInstance(self._version, payload, id=self._solution["id"]) def __repr__(self) -> str: @@ -74,7 +76,7 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ - return "" + return "" class ChunkList(ListResource): @@ -145,6 +147,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -164,6 +216,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -190,6 +243,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -198,6 +252,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -229,7 +333,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChunkPage(self._version, response, self._solution) + return ChunkPage(self._version, response, solution=self._solution) async def page_async( self, @@ -262,7 +366,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChunkPage(self._version, response, self._solution) + return ChunkPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChunkPage: """ @@ -274,7 +448,7 @@ def get_page(self, target_url: str) -> ChunkPage: :returns: Page of ChunkInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChunkPage(self._version, response, self._solution) + return ChunkPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChunkPage: """ @@ -286,7 +460,7 @@ async def get_page_async(self, target_url: str) -> ChunkPage: :returns: Page of ChunkInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChunkPage(self._version, response, self._solution) + return ChunkPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ @@ -294,4 +468,4 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/assistants/v1/knowledge/knowledge_status.py b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py similarity index 69% rename from twilio/rest/assistants/v1/knowledge/knowledge_status.py rename to twilio/rest/knowledge/v1/knowledge/knowledge_status.py index fedbcaad25..950318b3ac 100644 --- a/twilio/rest/assistants/v1/knowledge/knowledge_status.py +++ b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Assistants + Twilio - Knowledge This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], id: str): self._solution = { "id": id, } + self._context: Optional[KnowledgeStatusContext] = None @property @@ -77,6 +79,24 @@ async def fetch_async(self) -> "KnowledgeStatusInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -84,7 +104,7 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + return "".format(context) class KnowledgeStatusContext(InstanceContext): @@ -104,48 +124,96 @@ def __init__(self, version: Version, id: str): } self._uri = "/Knowledge/{id}/Status".format(**self._solution) - def fetch(self) -> KnowledgeStatusInstance: + def _fetch(self) -> tuple: """ - Fetch the KnowledgeStatusInstance + Internal helper for fetch operation - - :returns: The fetched KnowledgeStatusInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = self._fetch() return KnowledgeStatusInstance( self._version, payload, id=self._solution["id"], ) - async def fetch_async(self) -> KnowledgeStatusInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the KnowledgeStatusInstance + Fetch the KnowledgeStatusInstance and return response metadata - :returns: The fetched KnowledgeStatusInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> KnowledgeStatusInstance: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = await self._fetch_async() return KnowledgeStatusInstance( self._version, payload, id=self._solution["id"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -153,7 +221,7 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + return "".format(context) class KnowledgeStatusList(ListResource): @@ -193,4 +261,4 @@ def __repr__(self) -> str: :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/knowledge/v2/__init__.py b/twilio/rest/knowledge/v2/__init__.py new file mode 100644 index 0000000000..ac09c8bd51 --- /dev/null +++ b/twilio/rest/knowledge/v2/__init__.py @@ -0,0 +1,98 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.knowledge.v2.chunk import ChunkList +from twilio.rest.knowledge.v2.knowledge import KnowledgeList +from twilio.rest.knowledge.v2.knowledge_basis import KnowledgeBasisList +from twilio.rest.knowledge.v2.operation import OperationList +from twilio.rest.knowledge.v2.search import SearchList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Knowledge + + :param domain: The Twilio.knowledge domain + """ + super().__init__(domain, "v2") + self._knowledge_bases: Optional[KnowledgeBasisList] = None + self._operations: Optional[OperationList] = None + + def chunks(self, kb_id: str, knowledge_id: str, chunk_id: str = None): + """ + Access the ChunkList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + + :param chunk_id: Optional instance ID to directly access ChunkContext + :returns: ChunkList instance if chunk_id is None, otherwise ChunkContext + """ + list_instance = ChunkList(self, kb_id, knowledge_id) + if chunk_id is not None: + return list_instance(chunk_id) + return list_instance + + def knowledge(self, kb_id: str, knowledge_id: str = None): + """ + Access the KnowledgeList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param knowledge_id: Optional instance ID to directly access KnowledgeContext + :returns: KnowledgeList instance if knowledge_id is None, otherwise KnowledgeContext + """ + list_instance = KnowledgeList(self, kb_id) + if knowledge_id is not None: + return list_instance(knowledge_id) + return list_instance + + @property + def knowledge_bases(self) -> KnowledgeBasisList: + if self._knowledge_bases is None: + self._knowledge_bases = KnowledgeBasisList(self) + return self._knowledge_bases + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def search(self, kb_id: str, search_id: str = None): + """ + Access the SearchList resource + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + :param search_id: Optional instance ID to directly access SearchContext + :returns: SearchList instance if search_id is None, otherwise SearchContext + """ + list_instance = SearchList(self, kb_id) + if search_id is not None: + return list_instance(search_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/chunk.py b/twilio/rest/knowledge/v2/chunk.py new file mode 100644 index 0000000000..42b8e14f7a --- /dev/null +++ b/twilio/rest/knowledge/v2/chunk.py @@ -0,0 +1,515 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ChunkInstance(InstanceResource): + """ + :ivar content: The chunk content. + :ivar created_at: The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar chunk_index: 0-based position of this chunk within its source document for a single ingestion run. + :ivar document_title: Human-readable title of the source document. Web: HTML from the crawled page. File: filename from Unstructured metadata. Text: knowledge name from the knowledge source. + :ivar document_url: Specific page URL this chunk was crawled from. Web sources only; null for File and Text sources. + :ivar document_number: Physical page number (1-based). PDF sources only; omitted for all other source types. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], kb_id: str, knowledge_id: str + ): + super().__init__(version) + + self.content: Optional[str] = payload.get("content") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.chunk_index: Optional[int] = deserialize.integer(payload.get("chunkIndex")) + self.document_title: Optional[str] = payload.get("documentTitle") + self.document_url: Optional[str] = payload.get("documentUrl") + self.document_number: Optional[int] = deserialize.integer( + payload.get("documentNumber") + ) + + # Only set _solution if path params are provided (not None) + if kb_id is not None or knowledge_id is not None: + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.ChunkInstance {}>".format(context) + + +class ChunkPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ChunkInstance: + """ + Build an instance of ChunkInstance + + :param payload: Payload response from the API + """ + + return ChunkInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.ChunkPage>" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, kb_id: str, knowledge_id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge/{knowledge_id}/Chunks".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChunkInstance]: + """ + Streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_token=page_token, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChunkInstance]: + """ + Asynchronously streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Asynchronously lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChunkInstance and returns headers from first page + + + :param str page_token: The page token. This is provided by the API. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_size: How many resources to return in each list page. The default is 50, and the maximum is 1000. + :param page_token: The page token. This is provided by the API. + :returns: Page of ChunkInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_size: How many resources to return in each list page. The default is 50, and the maximum is 1000. + :param page_token: The page token. This is provided by the API. + :returns: Page of ChunkInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The page token. This is provided by the API. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChunkPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The page token. This is provided by the API. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChunkPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChunkPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ChunkPage: + """ + Retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChunkPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ChunkPage: + """ + Asynchronously retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChunkPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.ChunkList>" diff --git a/twilio/rest/knowledge/v2/knowledge.py b/twilio/rest/knowledge/v2/knowledge.py new file mode 100644 index 0000000000..dc40d54a9b --- /dev/null +++ b/twilio/rest/knowledge/v2/knowledge.py @@ -0,0 +1,1248 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class KnowledgeInstance(InstanceResource): + + class SupportedFileMimeType(object): + TEXT_CSV = "text/csv" + TEXT_MARKDOWN = "text/markdown" + APPLICATION_PDF = "application/pdf" + TEXT_TAB_SEPARATED_VALUES = "text/tab-separated-values" + TEXT_PLAIN = "text/plain" + + """ + :ivar name: The name of the knowledge source. + :ivar description: A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + :ivar source: + :ivar id: The unique identifier of knowledge source. + :ivar status: The status of processing the knowledge source ('SCHEDULED', 'QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED'). + :ivar created_at: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar updated_at: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar code: The Twilio error code. + :ivar message: A human readable message describing the error. + :ivar more_info: A URL to a [Twilio error directory](https://www.twilio.com/docs/api/errors) page with more information about the error code. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + kb_id: str, + knowledge_id: Optional[str] = None, + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.source: Optional[str] = payload.get("source") + self.id: Optional[str] = payload.get("id") + self.status: Optional["KnowledgeInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + + # Only set _solution if path params are provided (not None) + if kb_id is not None or knowledge_id is not None: + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + + self._context: Optional[KnowledgeContext] = None + + @property + def _proxy(self) -> "KnowledgeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeContext for this KnowledgeInstance + """ + if self._context is None: + self._context = KnowledgeContext( + self._version, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "KnowledgeInstance": + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeInstance": + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + async def update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + return await self._proxy.update_async( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + def update_with_http_info( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + async def update_with_http_info_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + refresh=refresh, + knowledge_core=knowledge_core, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.KnowledgeInstance {}>".format(context) + + +class KnowledgeContext(InstanceContext): + + def __init__(self, version: Version, kb_id: str, knowledge_id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + "knowledge_id": knowledge_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge/{knowledge_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = self._fetch() + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "refresh": serialize.boolean_to_string(refresh), + } + ) + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers, params=params + ) + + def update( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = self._update(refresh=refresh, knowledge_core=knowledge_core) + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + def update_with_http_info( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + refresh=refresh, knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + params = values.of( + { + "refresh": serialize.boolean_to_string(refresh), + } + ) + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers, params=params + ) + + async def update_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = await self._update_async( + refresh=refresh, knowledge_core=knowledge_core + ) + return KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + + async def update_with_http_info_async( + self, + refresh: Union[bool, object] = values.unset, + knowledge_core: Union[KnowledgeCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param refresh: When true, re-queues processing for this knowledge resource. Idempotent while the resource is already QUEUED or PROCESSING. + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + refresh=refresh, knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + knowledge_id=self._solution["knowledge_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.KnowledgeContext {}>".format(context) + + +class KnowledgePage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> KnowledgeInstance: + """ + Build an instance of KnowledgeInstance + + :param payload: Payload response from the API + """ + + return KnowledgeInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.KnowledgePage>" + + +class KnowledgeList(ListResource): + + class KnowledgeCore(object): + """ + :ivar name: The name of the knowledge source. + :ivar description: A detailed description of the knowledge source and when to use it. This helps provide context about the content and its intended purpose. + :ivar source: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.source: Optional[KnowledgeList.KnowledgeSourceTypes] = payload.get( + "source" + ) + + def to_dict(self): + return { + "name": self.name, + "description": self.description, + "source": self.source.to_dict() if self.source is not None else None, + } + + class KnowledgeSourceTypes(object): + """ + :ivar type: Raw text knowledge sources + :ivar content: The raw text content to be processed + :ivar url: The URL to crawl for web content + :ivar crawl_depth: The maximum depth to crawl from the source URL + :ivar crawl_period: Frequency of re-crawling the website for updated content + :ivar file_name: Name of the file to be uploaded + :ivar file_size: Expected size of the file in bytes + :ivar mime_type: + :ivar import_url: Presigned S3 URL for file upload (when status is SCHEDULED). Use PUT method to upload the file to this URL when status is SCHEDULED. + :ivar upload_expiration: Expiration time of the presigned upload URL in ISO 8601 format (only present when status is SCHEDULED) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["KnowledgeInstance.str"] = payload.get("type") + self.content: Optional[str] = payload.get("content") + self.url: Optional[str] = payload.get("url") + self.crawl_depth: Optional[int] = payload.get("crawlDepth") + self.crawl_period: Optional["KnowledgeInstance.str"] = payload.get( + "crawlPeriod" + ) + self.file_name: Optional[str] = payload.get("fileName") + self.file_size: Optional[int] = payload.get("fileSize") + self.mime_type: Optional["KnowledgeInstance.SupportedFileMimeType"] = ( + payload.get("mimeType") + ) + self.import_url: Optional[str] = payload.get("importUrl") + self.upload_expiration: Optional[datetime] = payload.get("uploadExpiration") + + def to_dict(self): + return { + "type": self.type, + "content": self.content, + "url": self.url, + "crawlDepth": self.crawl_depth, + "crawlPeriod": self.crawl_period, + "fileName": self.file_name, + "fileSize": self.file_size, + "mimeType": self.mime_type, + "importUrl": self.import_url, + "uploadExpiration": self.upload_expiration, + } + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Knowledge".format(**self._solution) + + def _create(self, knowledge_core: KnowledgeCore) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, knowledge_core: KnowledgeCore) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param knowledge_core: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = self._create(knowledge_core=knowledge_core) + return KnowledgeInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + def create_with_http_info(self, knowledge_core: KnowledgeCore) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(knowledge_core=knowledge_core) + instance = KnowledgeInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, knowledge_core: KnowledgeCore) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, knowledge_core: KnowledgeCore) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param knowledge_core: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = await self._create_async(knowledge_core=knowledge_core) + return KnowledgeInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + async def create_with_http_info_async( + self, knowledge_core: KnowledgeCore + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param knowledge_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_core=knowledge_core + ) + instance = KnowledgeInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KnowledgeInstance]: + """ + Streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KnowledgeInstance]: + """ + Asynchronously streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page=page, page_token=page_token, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Asynchronously lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeInstance and returns headers from first page + + + :param int page: The page index. This value is simply for client state. + :param str page_token: The token for the page of results to retrieve. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page=page, + page_token=page_token, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param page: The page index. This value is simply for client state. + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "page": page, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param page: The page index. This value is simply for client state. + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "page": page, + "pageSize": page_size, + "pageToken": page_token, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page: The page index. This value is simply for client state. + :param page_token: The token for the page of results to retrieve. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "page": page, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgePage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page: The page index. This value is simply for client state. + :param page_token: The token for the page of results to retrieve. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgePage, status code, and headers + """ + data = values.of( + { + "page": page, + "pageToken": page_token, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> KnowledgePage: + """ + Retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KnowledgePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> KnowledgePage: + """ + Asynchronously retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KnowledgePage(self._version, response, solution=self._solution) + + def get(self, knowledge_id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + return KnowledgeContext( + self._version, kb_id=self._solution["kb_id"], knowledge_id=knowledge_id + ) + + def __call__(self, knowledge_id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param knowledge_id: A unique Knowledge resource ID using Twilio Type ID (TTID) format + """ + return KnowledgeContext( + self._version, kb_id=self._solution["kb_id"], knowledge_id=knowledge_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.KnowledgeList>" diff --git a/twilio/rest/knowledge/v2/knowledge_basis.py b/twilio/rest/knowledge/v2/knowledge_basis.py new file mode 100644 index 0000000000..d4fa29ac7d --- /dev/null +++ b/twilio/rest/knowledge/v2/knowledge_basis.py @@ -0,0 +1,1172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class KnowledgeBasisInstance(InstanceResource): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + :ivar id: The unique identifier for the Knowledge Base + :ivar status: The provisioning status of the Knowledge Base + :ivar created_at: The ISO 8601 timestamp when the Knowledge Base was created. + :ivar updated_at: The ISO 8601 timestamp when the Knowledge Base was last updated. + :ivar version: The current version number of the Knowledge Base. Incremented on each successful mutable update. + :ivar message: + :ivar status_url: URI to check operation status. + """ + + def __init__( + self, version: Version, payload: ResponseResource, kb_id: Optional[str] = None + ): + super().__init__(version) + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.status: Optional["KnowledgeBasisInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + + # Only set _solution if path params are provided (not None) + if kb_id is not None: + self._solution = { + "kb_id": kb_id, + } + + self._context: Optional[KnowledgeBasisContext] = None + + @property + def _proxy(self) -> "KnowledgeBasisContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeBasisContext for this KnowledgeBasisInstance + """ + if self._context is None: + self._context = KnowledgeBasisContext( + self._version, + kb_id=self._solution["kb_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "KnowledgeBasisInstance": + """ + Fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeBasisInstance": + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> "KnowledgeBasisInstance": + """ + Update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + return self._proxy.update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + async def update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> "KnowledgeBasisInstance": + """ + Asynchronous coroutine to update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + return await self._proxy.update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + def update_with_http_info( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeBasisInstance with HTTP info + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance with HTTP info + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.KnowledgeBasisInstance {}>".format(context) + + +class KnowledgeBasisContext(InstanceContext): + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the KnowledgeBasisContext + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/ControlPlane/KnowledgeBases/{kb_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeBasisInstance: + """ + Fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + payload, _, _ = self._fetch() + return KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> KnowledgeBasisInstance: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance + + + :returns: The fetched KnowledgeBasisInstance + """ + payload, _, _ = await self._fetch_async() + return KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KnowledgeBasisInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = KnowledgeBasisInstance( + self._version, + payload, + kb_id=self._solution["kb_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_knowledge_base_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> KnowledgeBasisInstance: + """ + Update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + payload, _, _ = self._update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + return KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + + def update_with_http_info( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeBasisInstance and return response metadata + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + instance = KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_knowledge_base_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> KnowledgeBasisInstance: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated KnowledgeBasisInstance + """ + payload, _, _ = await self._update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + return KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + + async def update_with_http_info_async( + self, + update_knowledge_base_request: UpdateKnowledgeBaseRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeBasisInstance and return response metadata + + :param update_knowledge_base_request: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_knowledge_base_request=update_knowledge_base_request, + if_match=if_match, + ) + instance = KnowledgeBasisInstance( + self._version, payload, kb_id=self._solution["kb_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.KnowledgeBasisContext {}>".format(context) + + +class KnowledgeBasisPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> KnowledgeBasisInstance: + """ + Build an instance of KnowledgeBasisInstance + + :param payload: Payload response from the API + """ + + return KnowledgeBasisInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.KnowledgeBasisPage>" + + +class KnowledgeBasisList(ListResource): + + class KnowledgeBaseCore(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + class UpdateKnowledgeBaseRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Knowledge Base. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeBasisList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/KnowledgeBases" + + def _create(self, knowledge_base_core: KnowledgeBaseCore) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_base_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, knowledge_base_core: KnowledgeBaseCore) -> KnowledgeBasisInstance: + """ + Create the KnowledgeBasisInstance + + :param knowledge_base_core: + + :returns: The created KnowledgeBasisInstance + """ + payload, _, _ = self._create(knowledge_base_core=knowledge_base_core) + return KnowledgeBasisInstance(self._version, payload) + + def create_with_http_info( + self, knowledge_base_core: KnowledgeBaseCore + ) -> ApiResponse: + """ + Create the KnowledgeBasisInstance and return response metadata + + :param knowledge_base_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + knowledge_base_core=knowledge_base_core + ) + instance = KnowledgeBasisInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, knowledge_base_core: KnowledgeBaseCore) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_base_core.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, knowledge_base_core: KnowledgeBaseCore + ) -> KnowledgeBasisInstance: + """ + Asynchronously create the KnowledgeBasisInstance + + :param knowledge_base_core: + + :returns: The created KnowledgeBasisInstance + """ + payload, _, _ = await self._create_async( + knowledge_base_core=knowledge_base_core + ) + return KnowledgeBasisInstance(self._version, payload) + + async def create_with_http_info_async( + self, knowledge_base_core: KnowledgeBaseCore + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeBasisInstance and return response metadata + + :param knowledge_base_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_base_core=knowledge_base_core + ) + instance = KnowledgeBasisInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KnowledgeBasisInstance]: + """ + Streams KnowledgeBasisInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KnowledgeBasisInstance]: + """ + Asynchronously streams KnowledgeBasisInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeBasisInstance]: + """ + Lists KnowledgeBasisInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeBasisInstance]: + """ + Asynchronously lists KnowledgeBasisInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists KnowledgeBasisInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> KnowledgeBasisPage: + """ + Retrieve a single page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of KnowledgeBasisInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgeBasisPage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> KnowledgeBasisPage: + """ + Asynchronously retrieve a single page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of KnowledgeBasisInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgeBasisPage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgeBasisPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = KnowledgeBasisPage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with KnowledgeBasisPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = KnowledgeBasisPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> KnowledgeBasisPage: + """ + Retrieve a specific page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeBasisInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KnowledgeBasisPage(self._version, response) + + async def get_page_async(self, target_url: str) -> KnowledgeBasisPage: + """ + Asynchronously retrieve a specific page of KnowledgeBasisInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeBasisInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KnowledgeBasisPage(self._version, response) + + def get(self, kb_id: str) -> KnowledgeBasisContext: + """ + Constructs a KnowledgeBasisContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return KnowledgeBasisContext(self._version, kb_id=kb_id) + + def __call__(self, kb_id: str) -> KnowledgeBasisContext: + """ + Constructs a KnowledgeBasisContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return KnowledgeBasisContext(self._version, kb_id=kb_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.KnowledgeBasisList>" diff --git a/twilio/rest/knowledge/v2/operation.py b/twilio/rest/knowledge/v2/operation.py new file mode 100644 index 0000000000..e967c1d8bd --- /dev/null +++ b/twilio/rest/knowledge/v2/operation.py @@ -0,0 +1,279 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperationInstance(InstanceResource): + """ + :ivar operation_id: The unique identifier for this operation. + :ivar status: The current status of the operation. + :ivar created_at: When the operation was created. + :ivar status_url: URI to check operation status. + :ivar completed_at: When the operation completed or failed. + :ivar result: + :ivar error: + :ivar result_url: URL to fetch the resulting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + operation_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.result: Optional[str] = payload.get("result") + self.error: Optional[str] = payload.get("error") + self.result_url: Optional[str] = payload.get("resultUrl") + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + operation_id=self._solution["operation_id"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.OperationInstance {}>".format(context) + + +class OperationContext(InstanceContext): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param operation_id: The operation ID returned from a write endpoint. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = "/ControlPlane/Operations/{operation_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.OperationContext {}>".format(context) + + +class OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __call__(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.OperationList>" diff --git a/twilio/rest/knowledge/v2/search.py b/twilio/rest/knowledge/v2/search.py new file mode 100644 index 0000000000..38ac0a573d --- /dev/null +++ b/twilio/rest/knowledge/v2/search.py @@ -0,0 +1,194 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Knowledge API + APIs for managing knowledge bases and knowledge content for AI-powered applications. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SearchInstance(InstanceResource): + """ + :ivar chunks: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], kb_id: str): + super().__init__(version) + + self.chunks: Optional[List[str]] = payload.get("chunks") + + # Only set _solution if path params are provided (not None) + if kb_id is not None: + self._solution = { + "kb_id": kb_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Knowledge.V2.SearchInstance {}>".format(context) + + +class SearchList(ListResource): + + class KnowledgeSearch(object): + """ + :ivar query: The query to search the knowledge source. + :ivar top: The top K results to return. + :ivar knowledge_ids: The list of knowledge IDs to search. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.query: Optional[str] = payload.get("query") + self.top: Optional[int] = payload.get("top") + self.knowledge_ids: Optional[List[str]] = payload.get("knowledgeIds") + + def to_dict(self): + return { + "query": self.query, + "top": self.top, + "knowledgeIds": self.knowledge_ids, + } + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the SearchList + + :param version: Version that contains the resource + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "kb_id": kb_id, + } + self._uri = "/KnowledgeBases/{kb_id}/Search".format(**self._solution) + + def _create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_search.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> SearchInstance: + """ + Create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + payload, _, _ = self._create(knowledge_search=knowledge_search) + return SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + def create_with_http_info( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Create the SearchInstance and return response metadata + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(knowledge_search=knowledge_search) + instance = SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_search.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> SearchInstance: + """ + Asynchronously create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + payload, _, _ = await self._create_async(knowledge_search=knowledge_search) + return SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + + async def create_with_http_info_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the SearchInstance and return response metadata + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + knowledge_search=knowledge_search + ) + instance = SearchInstance(self._version, payload, kb_id=self._solution["kb_id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Knowledge.V2.SearchList>" diff --git a/twilio/rest/lookups/v1/phone_number.py b/twilio/rest/lookups/v1/phone_number.py index ace46b67bd..66ac1d0d6e 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -78,7 +80,7 @@ def fetch( Fetch the PhoneNumberInstance :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. @@ -102,7 +104,7 @@ async def fetch_async( Asynchronous coroutine to fetch the PhoneNumberInstance :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. @@ -115,6 +117,54 @@ async def fetch_async( add_ons_data=add_ons_data, ) + def fetch_with_http_info( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + async def fetch_with_http_info_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,25 +192,21 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - def fetch( + def _fetch( self, country_code: Union[str, object] = values.unset, type: Union[List[str], object] = values.unset, add_ons: Union[List[str], object] = values.unset, add_ons_data: Union[Dict[str, object], object] = values.unset, - ) -> PhoneNumberInstance: + ) -> tuple: """ - Fetch the PhoneNumberInstance + Internal helper for fetch operation - :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. - :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). - :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. - - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "CountryCode": country_code, "Type": serialize.map(type, lambda e: e), @@ -168,41 +214,90 @@ def fetch( } ) - data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async( + def fetch_with_http_info( self, country_code: Union[str, object] = values.unset, type: Union[List[str], object] = values.unset, add_ons: Union[List[str], object] = values.unset, add_ons_data: Union[Dict[str, object], object] = values.unset, - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "CountryCode": country_code, "Type": serialize.map(type, lambda e: e), @@ -210,22 +305,75 @@ async def fetch_async( } ) - data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) + async def fetch_with_http_info_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/lookups/v2/__init__.py b/twilio/rest/lookups/v2/__init__.py index d795aea168..852f552540 100644 --- a/twilio/rest/lookups/v2/__init__.py +++ b/twilio/rest/lookups/v2/__init__.py @@ -15,7 +15,11 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.lookups.v2.bucket import BucketList +from twilio.rest.lookups.v2.lookup_override import LookupOverrideList from twilio.rest.lookups.v2.phone_number import PhoneNumberList +from twilio.rest.lookups.v2.query import QueryList +from twilio.rest.lookups.v2.rate_limit import RateLimitList class V2(Version): @@ -27,7 +31,23 @@ def __init__(self, domain: Domain): :param domain: The Twilio.lookups domain """ super().__init__(domain, "v2") + self._bucket: Optional[BucketList] = None + self._lookup_overrides: Optional[LookupOverrideList] = None self._phone_numbers: Optional[PhoneNumberList] = None + self._query: Optional[QueryList] = None + self._rate_limits: Optional[RateLimitList] = None + + @property + def bucket(self) -> BucketList: + if self._bucket is None: + self._bucket = BucketList(self) + return self._bucket + + @property + def lookup_overrides(self) -> LookupOverrideList: + if self._lookup_overrides is None: + self._lookup_overrides = LookupOverrideList(self) + return self._lookup_overrides @property def phone_numbers(self) -> PhoneNumberList: @@ -35,6 +55,18 @@ def phone_numbers(self) -> PhoneNumberList: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers + @property + def query(self) -> QueryList: + if self._query is None: + self._query = QueryList(self) + return self._query + + @property + def rate_limits(self) -> RateLimitList: + if self._rate_limits is None: + self._rate_limits = RateLimitList(self) + return self._rate_limits + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/lookups/v2/bucket.py b/twilio/rest/lookups/v2/bucket.py new file mode 100644 index 0000000000..ce020fa8f3 --- /dev/null +++ b/twilio/rest/lookups/v2/bucket.py @@ -0,0 +1,621 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BucketInstance(InstanceResource): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + """ + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + :ivar field: Limit of requests for the bucket + :ivar limit: Limit of requests for the bucket + :ivar bucket: Name of the bucket + :ivar owner: Owner of the rule + :ivar ttl: Time to live of the rule + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + field: Optional[str] = None, + bucket: Optional[str] = None, + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = payload.get("status") + self.field: Optional[str] = payload.get("field") + self.limit: Optional[int] = payload.get("limit") + self.bucket: Optional[str] = payload.get("bucket") + self.owner: Optional[str] = payload.get("owner") + self.ttl: Optional[int] = payload.get("ttl") + + self._solution = { + "field": field or self.field, + "bucket": bucket or self.bucket, + } + + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BucketContext for this BucketInstance + """ + if self._context is None: + self._context = BucketContext( + self._version, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return self._proxy.update( + rate_limit_request=rate_limit_request, + ) + + async def update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + rate_limit_request=rate_limit_request, + ) + + def update_with_http_info( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + rate_limit_request=rate_limit_request, + ) + + async def update_with_http_info_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + rate_limit_request=rate_limit_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.BucketInstance {}>".format(context) + + +class BucketContext(InstanceContext): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + def __init__(self, version: Version, field: str, bucket: str): + """ + Initialize the BucketContext + + :param version: Version that contains the resource + :param field: field name + :param bucket: bucket name + """ + super().__init__(version) + + # Path Solution + self._solution = { + "field": field, + "bucket": bucket, + } + self._uri = "/RateLimits/Fields/{field}/Bucket/{bucket}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = self._fetch() + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> BucketInstance: + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = await self._fetch_async() + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = rate_limit_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> BucketInstance: + """ + Update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + payload, _, _ = self._update(rate_limit_request=rate_limit_request) + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + def update_with_http_info( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the BucketInstance and return response metadata + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + rate_limit_request=rate_limit_request + ) + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = rate_limit_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> BucketInstance: + """ + Asynchronous coroutine to update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + payload, _, _ = await self._update_async(rate_limit_request=rate_limit_request) + return BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + + async def update_with_http_info_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance and return response metadata + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + rate_limit_request=rate_limit_request + ) + instance = BucketInstance( + self._version, + payload, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.BucketContext {}>".format(context) + + +class BucketList(ListResource): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + def __init__(self, version: Version): + """ + Initialize the BucketList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, field: str, bucket: str) -> BucketContext: + """ + Constructs a BucketContext + + :param field: field name + :param bucket: bucket name + """ + return BucketContext(self._version, field=field, bucket=bucket) + + def __call__(self, field: str, bucket: str) -> BucketContext: + """ + Constructs a BucketContext + + :param field: field name + :param bucket: bucket name + """ + return BucketContext(self._version, field=field, bucket=bucket) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2.BucketList>" diff --git a/twilio/rest/lookups/v2/lookup_override.py b/twilio/rest/lookups/v2/lookup_override.py new file mode 100644 index 0000000000..ea3cd6b389 --- /dev/null +++ b/twilio/rest/lookups/v2/lookup_override.py @@ -0,0 +1,828 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LookupOverrideInstance(InstanceResource): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + """ + :ivar phone_number: The phone number for which the override was created + :ivar original_line_type: The original line type + :ivar overridden_line_type: The new line type after the override + :ivar override_reason: The reason for the override + :ivar override_timestamp: + :ivar overridden_by_account_sid: The Account SID for the user who made the override + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + :ivar field: Limit of requests for the bucket + :ivar limit: Limit of requests for the bucket + :ivar bucket: Name of the bucket + :ivar owner: Owner of the rule + :ivar ttl: Time to live of the rule + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + field: Optional[str] = None, + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.original_line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "original_line_type" + ) + self.overridden_line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "overridden_line_type" + ) + self.override_reason: Optional[str] = payload.get("override_reason") + self.override_timestamp: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("override_timestamp") + ) + self.overridden_by_account_sid: Optional[str] = payload.get( + "overridden_by_account_sid" + ) + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = payload.get("status") + self.field: Optional[str] = payload.get("field") + self.limit: Optional[int] = payload.get("limit") + self.bucket: Optional[str] = payload.get("bucket") + self.owner: Optional[str] = payload.get("owner") + self.ttl: Optional[int] = payload.get("ttl") + + self._solution = { + "field": field or self.field, + "phone_number": phone_number or self.phone_number, + } + + self._context: Optional[LookupOverrideContext] = None + + @property + def _proxy(self) -> "LookupOverrideContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LookupOverrideContext for this LookupOverrideInstance + """ + if self._context is None: + self._context = LookupOverrideContext( + self._version, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return self._context + + def create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + return self._proxy.create( + overrides_request=overrides_request, + ) + + async def create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + return await self._proxy.create_async( + overrides_request=overrides_request, + ) + + def create_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + overrides_request=overrides_request, + ) + + async def create_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + overrides_request=overrides_request, + ) + + def delete(self) -> bool: + """ + Deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "LookupOverrideInstance": + """ + Fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + return self._proxy.update( + overrides_request=overrides_request, + ) + + async def update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> "LookupOverrideInstance": + """ + Asynchronous coroutine to update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + return await self._proxy.update_async( + overrides_request=overrides_request, + ) + + def update_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + overrides_request=overrides_request, + ) + + async def update_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the LookupOverrideInstance with HTTP info + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + overrides_request=overrides_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.LookupOverrideInstance {}>".format(context) + + +class LookupOverrideContext(InstanceContext): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + def __init__(self, version: Version, field: str, phone_number: str): + """ + Initialize the LookupOverrideContext + + :param version: Version that contains the resource + :param field: + :param phone_number: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "field": field, + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}/Overrides/{field}".format( + **self._solution + ) + + def _create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + payload, _, _ = self._create(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def create_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Asynchronous coroutine to create the LookupOverrideInstance + + :param overrides_request: + + :returns: The created LookupOverrideInstance + """ + payload, _, _ = await self._create_async(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def create_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> LookupOverrideInstance: + """ + Fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + payload, _, _ = self._fetch() + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> LookupOverrideInstance: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance + + + :returns: The fetched LookupOverrideInstance + """ + payload, _, _ = await self._fetch_async() + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LookupOverrideInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + payload, _, _ = self._update(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + def update_with_http_info( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = overrides_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> LookupOverrideInstance: + """ + Asynchronous coroutine to update the LookupOverrideInstance + + :param overrides_request: + + :returns: The updated LookupOverrideInstance + """ + payload, _, _ = await self._update_async(overrides_request=overrides_request) + return LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + + async def update_with_http_info_async( + self, overrides_request: Union[OverridesRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the LookupOverrideInstance and return response metadata + + :param overrides_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + overrides_request=overrides_request + ) + instance = LookupOverrideInstance( + self._version, + payload, + field=self._solution["field"], + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.LookupOverrideContext {}>".format(context) + + +class LookupOverrideList(ListResource): + + class OverridesRequest(object): + """ + :ivar line_type: The new line type to override the original line type + :ivar reason: The reason for the override + """ + + def __init__(self, payload: Dict[str, Any]): + + self.line_type: Optional["LookupOverrideInstance.str"] = payload.get( + "line_type" + ) + self.reason: Optional[str] = payload.get("reason") + + def to_dict(self): + return { + "line_type": self.line_type, + "reason": self.reason, + } + + def __init__(self, version: Version): + """ + Initialize the LookupOverrideList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, field: str, phone_number: str) -> LookupOverrideContext: + """ + Constructs a LookupOverrideContext + + :param field: + :param phone_number: + """ + return LookupOverrideContext( + self._version, field=field, phone_number=phone_number + ) + + def __call__(self, field: str, phone_number: str) -> LookupOverrideContext: + """ + Constructs a LookupOverrideContext + + :param field: + :param phone_number: + """ + return LookupOverrideContext( + self._version, field=field, phone_number=phone_number + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2.LookupOverrideList>" diff --git a/twilio/rest/lookups/v2/phone_number.py b/twilio/rest/lookups/v2/phone_number.py index ac1b3257ef..2240351721 100644 --- a/twilio/rest/lookups/v2/phone_number.py +++ b/twilio/rest/lookups/v2/phone_number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -37,14 +38,14 @@ class ValidationError(object): :ivar national_format: The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers). :ivar valid: Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user. :ivar validation_errors: Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. - :ivar caller_name: An object that contains caller name information based on [CNAM](https://support.twilio.com/hc/en-us/articles/360051670533-Getting-Started-with-CNAM-Caller-ID). - :ivar sim_swap: An object that contains information on the last date the subscriber identity module (SIM) was changed for a mobile phone number. - :ivar call_forwarding: An object that contains information on the unconditional call forwarding status of mobile phone number. - :ivar line_status: An object that contains line status information for a mobile phone number. - :ivar line_type_intelligence: An object that contains line type information including the carrier name, mobile country code, and mobile network code. - :ivar identity_match: An object that contains identity match information. The result of comparing user-provided information including name, address, date of birth, national ID, against authoritative phone-based data sources - :ivar reassigned_number: An object that contains reassigned number information. Reassigned Numbers will return a phone number's reassignment status given a phone number and date - :ivar sms_pumping_risk: An object that contains information on if a phone number has been currently or previously blocked by Verify Fraud Guard for receiving malicious SMS pumping traffic as well as other signals associated with risky carriers and low conversion rates. + :ivar caller_name: + :ivar sim_swap: + :ivar call_forwarding: + :ivar line_type_intelligence: + :ivar line_status: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: :ivar phone_number_quality_score: An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number. :ivar pre_fill: An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. :ivar url: The absolute URL of the resource. @@ -63,25 +64,19 @@ def __init__( self.phone_number: Optional[str] = payload.get("phone_number") self.national_format: Optional[str] = payload.get("national_format") self.valid: Optional[bool] = payload.get("valid") - self.validation_errors: Optional[ - List["PhoneNumberInstance.ValidationError"] - ] = payload.get("validation_errors") - self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") - self.sim_swap: Optional[Dict[str, object]] = payload.get("sim_swap") - self.call_forwarding: Optional[Dict[str, object]] = payload.get( - "call_forwarding" + self.validation_errors: Optional[List[Enumstr]] = payload.get( + "validation_errors" ) - self.line_status: Optional[Dict[str, object]] = payload.get("line_status") - self.line_type_intelligence: Optional[Dict[str, object]] = payload.get( + self.caller_name: Optional[str] = payload.get("caller_name") + self.sim_swap: Optional[str] = payload.get("sim_swap") + self.call_forwarding: Optional[str] = payload.get("call_forwarding") + self.line_type_intelligence: Optional[str] = payload.get( "line_type_intelligence" ) - self.identity_match: Optional[Dict[str, object]] = payload.get("identity_match") - self.reassigned_number: Optional[Dict[str, object]] = payload.get( - "reassigned_number" - ) - self.sms_pumping_risk: Optional[Dict[str, object]] = payload.get( - "sms_pumping_risk" - ) + self.line_status: Optional[str] = payload.get("line_status") + self.identity_match: Optional[str] = payload.get("identity_match") + self.reassigned_number: Optional[str] = payload.get("reassigned_number") + self.sms_pumping_risk: Optional[str] = payload.get("sms_pumping_risk") self.phone_number_quality_score: Optional[Dict[str, object]] = payload.get( "phone_number_quality_score" ) @@ -91,6 +86,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -124,6 +120,7 @@ def fetch( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, ) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -142,6 +139,7 @@ def fetch( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. :returns: The fetched PhoneNumberInstance """ @@ -160,6 +158,7 @@ def fetch( date_of_birth=date_of_birth, last_verified_date=last_verified_date, verification_sid=verification_sid, + partner_sub_id=partner_sub_id, ) async def fetch_async( @@ -178,6 +177,7 @@ async def fetch_async( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, ) -> "PhoneNumberInstance": """ Asynchronous coroutine to fetch the PhoneNumberInstance @@ -196,6 +196,7 @@ async def fetch_async( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. :returns: The fetched PhoneNumberInstance """ @@ -214,6 +215,121 @@ async def fetch_async( date_of_birth=date_of_birth, last_verified_date=last_verified_date, verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + def fetch_with_http_info( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + async def fetch_with_http_info_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, ) def __repr__(self) -> str: @@ -243,7 +359,7 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - def fetch( + def _fetch( self, fields: Union[str, object] = values.unset, country_code: Union[str, object] = values.unset, @@ -259,29 +375,16 @@ def fetch( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + partner_sub_id: Union[str, object] = values.unset, + ) -> tuple: """ - Fetch the PhoneNumberInstance - - :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. - :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. - :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. - :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. - :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. - :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. - :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. - :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. - :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. - :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. - :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. - :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. - :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. - :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Fields": fields, "CountryCode": country_code, @@ -297,6 +400,7 @@ def fetch( "DateOfBirth": date_of_birth, "LastVerifiedDate": last_verified_date, "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, } ) @@ -304,17 +408,73 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async( + def fetch_with_http_info( self, fields: Union[str, object] = values.unset, country_code: Union[str, object] = values.unset, @@ -330,9 +490,10 @@ async def fetch_async( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. @@ -348,11 +509,60 @@ async def fetch_async( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Fields": fields, "CountryCode": country_code, @@ -368,6 +578,7 @@ async def fetch_async( "DateOfBirth": date_of_birth, "LastVerifiedDate": last_verified_date, "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, } ) @@ -375,16 +586,135 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) + async def fetch_with_http_info_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/lookups/v2/query.py b/twilio/rest/lookups/v2/query.py new file mode 100644 index 0000000000..1bb3ff6cc5 --- /dev/null +++ b/twilio/rest/lookups/v2/query.py @@ -0,0 +1,489 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class QueryInstance(InstanceResource): + + class IdentityMatchParameters(object): + """ + :ivar first_name: + :ivar last_name: + :ivar address_line1: + :ivar address_line2: + :ivar city: + :ivar state: + :ivar postal_code: + :ivar address_country_code: + :ivar national_id: + :ivar date_of_birth: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.first_name: Optional[str] = payload.get("first_name") + self.last_name: Optional[str] = payload.get("last_name") + self.address_line1: Optional[str] = payload.get("address_line1") + self.address_line2: Optional[str] = payload.get("address_line2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.postal_code: Optional[str] = payload.get("postal_code") + self.address_country_code: Optional[str] = payload.get( + "address_country_code" + ) + self.national_id: Optional[str] = payload.get("national_id") + self.date_of_birth: Optional[str] = payload.get("date_of_birth") + + def to_dict(self): + return { + "first_name": self.first_name, + "last_name": self.last_name, + "address_line1": self.address_line1, + "address_line2": self.address_line2, + "city": self.city, + "state": self.state, + "postal_code": self.postal_code, + "address_country_code": self.address_country_code, + "national_id": self.national_id, + "date_of_birth": self.date_of_birth, + } + + class LastSimSwapInfo(object): + """ + :ivar last_sim_swap_date: + :ivar swapped_period: + :ivar swapped_in_period: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_sim_swap_date: Optional[datetime] = payload.get( + "last_sim_swap_date" + ) + self.swapped_period: Optional[str] = payload.get("swapped_period") + self.swapped_in_period: Optional[bool] = payload.get("swapped_in_period") + + def to_dict(self): + return { + "last_sim_swap_date": self.last_sim_swap_date, + "swapped_period": self.swapped_period, + "swapped_in_period": self.swapped_in_period, + } + + class LookupBatchRequest(object): + """ + :ivar correlation_id: Unique identifier used to match request with response + :ivar phone_number: + :ivar fields: + :ivar country_code: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.correlation_id: Optional[str] = payload.get("correlation_id") + self.phone_number: Optional[str] = payload.get("phone_number") + self.fields: Optional[List[Enumstr]] = payload.get("fields") + self.country_code: Optional[str] = payload.get("country_code") + self.identity_match: Optional[QueryList.IdentityMatchParameters] = ( + payload.get("identity_match") + ) + self.reassigned_number: Optional[QueryList.ReassignedNumberParameters] = ( + payload.get("reassigned_number") + ) + self.sms_pumping_risk: Optional[QueryList.RiskParameters] = payload.get( + "sms_pumping_risk" + ) + + def to_dict(self): + return { + "correlation_id": self.correlation_id, + "phone_number": self.phone_number, + "fields": self.fields, + "country_code": self.country_code, + "identity_match": ( + self.identity_match.to_dict() + if self.identity_match is not None + else None + ), + "reassigned_number": ( + self.reassigned_number.to_dict() + if self.reassigned_number is not None + else None + ), + "sms_pumping_risk": ( + self.sms_pumping_risk.to_dict() + if self.sms_pumping_risk is not None + else None + ), + } + + class LookupRequest(object): + """ + :ivar phone_numbers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_numbers: Optional[List[QueryList.LookupBatchRequest]] = ( + payload.get("phone_numbers") + ) + + def to_dict(self): + return { + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + } + + class ReassignedNumberParameters(object): + """ + :ivar last_verified_date: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_verified_date: Optional[str] = payload.get("last_verified_date") + + def to_dict(self): + return { + "last_verified_date": self.last_verified_date, + } + + class RiskParameters(object): + """ + :ivar partner_sub_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.partner_sub_id: Optional[str] = payload.get("partner_sub_id") + + def to_dict(self): + return { + "partner_sub_id": self.partner_sub_id, + } + + """ + :ivar phone_numbers: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.phone_numbers: Optional[List[str]] = payload.get("phone_numbers") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Lookups.V2.QueryInstance>" + + +class QueryList(ListResource): + + class IdentityMatchParameters(object): + """ + :ivar first_name: + :ivar last_name: + :ivar address_line1: + :ivar address_line2: + :ivar city: + :ivar state: + :ivar postal_code: + :ivar address_country_code: + :ivar national_id: + :ivar date_of_birth: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.first_name: Optional[str] = payload.get("first_name") + self.last_name: Optional[str] = payload.get("last_name") + self.address_line1: Optional[str] = payload.get("address_line1") + self.address_line2: Optional[str] = payload.get("address_line2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.postal_code: Optional[str] = payload.get("postal_code") + self.address_country_code: Optional[str] = payload.get( + "address_country_code" + ) + self.national_id: Optional[str] = payload.get("national_id") + self.date_of_birth: Optional[str] = payload.get("date_of_birth") + + def to_dict(self): + return { + "first_name": self.first_name, + "last_name": self.last_name, + "address_line1": self.address_line1, + "address_line2": self.address_line2, + "city": self.city, + "state": self.state, + "postal_code": self.postal_code, + "address_country_code": self.address_country_code, + "national_id": self.national_id, + "date_of_birth": self.date_of_birth, + } + + class LastSimSwapInfo(object): + """ + :ivar last_sim_swap_date: + :ivar swapped_period: + :ivar swapped_in_period: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_sim_swap_date: Optional[datetime] = payload.get( + "last_sim_swap_date" + ) + self.swapped_period: Optional[str] = payload.get("swapped_period") + self.swapped_in_period: Optional[bool] = payload.get("swapped_in_period") + + def to_dict(self): + return { + "last_sim_swap_date": self.last_sim_swap_date, + "swapped_period": self.swapped_period, + "swapped_in_period": self.swapped_in_period, + } + + class LookupBatchRequest(object): + """ + :ivar correlation_id: Unique identifier used to match request with response + :ivar phone_number: + :ivar fields: + :ivar country_code: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.correlation_id: Optional[str] = payload.get("correlation_id") + self.phone_number: Optional[str] = payload.get("phone_number") + self.fields: Optional[List[Enumstr]] = payload.get("fields") + self.country_code: Optional[str] = payload.get("country_code") + self.identity_match: Optional[QueryList.IdentityMatchParameters] = ( + payload.get("identity_match") + ) + self.reassigned_number: Optional[QueryList.ReassignedNumberParameters] = ( + payload.get("reassigned_number") + ) + self.sms_pumping_risk: Optional[QueryList.RiskParameters] = payload.get( + "sms_pumping_risk" + ) + + def to_dict(self): + return { + "correlation_id": self.correlation_id, + "phone_number": self.phone_number, + "fields": self.fields, + "country_code": self.country_code, + "identity_match": ( + self.identity_match.to_dict() + if self.identity_match is not None + else None + ), + "reassigned_number": ( + self.reassigned_number.to_dict() + if self.reassigned_number is not None + else None + ), + "sms_pumping_risk": ( + self.sms_pumping_risk.to_dict() + if self.sms_pumping_risk is not None + else None + ), + } + + class LookupRequest(object): + """ + :ivar phone_numbers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_numbers: Optional[List[QueryList.LookupBatchRequest]] = ( + payload.get("phone_numbers") + ) + + def to_dict(self): + return { + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + } + + class ReassignedNumberParameters(object): + """ + :ivar last_verified_date: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.last_verified_date: Optional[str] = payload.get("last_verified_date") + + def to_dict(self): + return { + "last_verified_date": self.last_verified_date, + } + + class RiskParameters(object): + """ + :ivar partner_sub_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.partner_sub_id: Optional[str] = payload.get("partner_sub_id") + + def to_dict(self): + return { + "partner_sub_id": self.partner_sub_id, + } + + def __init__(self, version: Version): + """ + Initialize the QueryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/batch/query" + + def _create( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = lookup_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> QueryInstance: + """ + Create the QueryInstance + + :param lookup_request: + + :returns: The created QueryInstance + """ + payload, _, _ = self._create(lookup_request=lookup_request) + return QueryInstance(self._version, payload) + + def create_with_http_info( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the QueryInstance and return response metadata + + :param lookup_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(lookup_request=lookup_request) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = lookup_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> QueryInstance: + """ + Asynchronously create the QueryInstance + + :param lookup_request: + + :returns: The created QueryInstance + """ + payload, _, _ = await self._create_async(lookup_request=lookup_request) + return QueryInstance(self._version, payload) + + async def create_with_http_info_async( + self, lookup_request: Union[LookupRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the QueryInstance and return response metadata + + :param lookup_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + lookup_request=lookup_request + ) + instance = QueryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2.QueryList>" diff --git a/twilio/rest/lookups/v2/rate_limit.py b/twilio/rest/lookups/v2/rate_limit.py new file mode 100644 index 0000000000..71d6ce17e3 --- /dev/null +++ b/twilio/rest/lookups/v2/rate_limit.py @@ -0,0 +1,157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RateLimitInstance(InstanceResource): + """ + :ivar rate_limits: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.rate_limits: Optional[List[str]] = payload.get("rate_limits") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Lookups.V2.RateLimitInstance>" + + +class RateLimitList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RateLimitList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RateLimits" + + def _fetch(self, fields: Union[List[str], object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "Fields": fields, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, fields: Union[List[str], object] = values.unset + ) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + :param fields: + :returns: The fetched RateLimitInstance + """ + payload, _, _ = self._fetch(fields=fields) + return RateLimitInstance(self._version, payload) + + def fetch_with_http_info( + self, fields: Union[List[str], object] = values.unset + ) -> ApiResponse: + """ + Fetch the RateLimitInstance and return response metadata + + :param fields: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(fields=fields) + instance = RateLimitInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, fields: Union[List[str], object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "Fields": fields, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, fields: Union[List[str], object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously fetch the RateLimitInstance + + :param fields: + :returns: The fetched RateLimitInstance + """ + payload, _, _ = await self._fetch_async(fields=fields) + return RateLimitInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, fields: Union[List[str], object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the RateLimitInstance and return response metadata + + :param fields: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(fields=fields) + instance = RateLimitInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2.RateLimitList>" diff --git a/twilio/rest/marketplace/v1/available_add_on/__init__.py b/twilio/rest/marketplace/v1/available_add_on/__init__.py index 297d5dd6f3..53ed2aeb1d 100644 --- a/twilio/rest/marketplace/v1/available_add_on/__init__.py +++ b/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "AvailableAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -124,48 +144,96 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[AvailableAddOnExtensionList] = None - def fetch(self) -> AvailableAddOnInstance: + def _fetch(self) -> tuple: """ - Fetch the AvailableAddOnInstance - + Internal helper for fetch operation - :returns: The fetched AvailableAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = self._fetch() return AvailableAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AvailableAddOnInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AvailableAddOnInstance + Fetch the AvailableAddOnInstance and return response metadata - :returns: The fetched AvailableAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = await self._fetch_async() return AvailableAddOnInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -196,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: :param payload: Payload response from the API """ + return AvailableAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -270,6 +339,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -289,6 +408,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -315,6 +435,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -323,6 +444,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -389,6 +560,76 @@ async def page_async( ) return AvailableAddOnPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AvailableAddOnPage: """ Retrieve a specific page of AvailableAddOnInstance records from the API. diff --git a/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py index a8973a08b0..14dcfed3af 100644 --- a/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py +++ b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "available_add_on_sid": available_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnExtensionContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "AvailableAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -120,20 +140,30 @@ def __init__(self, version: Version, available_add_on_sid: str, sid: str): **self._solution ) - def fetch(self) -> AvailableAddOnExtensionInstance: + def _fetch(self) -> tuple: """ - Fetch the AvailableAddOnExtensionInstance - + Internal helper for fetch operation - :returns: The fetched AvailableAddOnExtensionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = self._fetch() return AvailableAddOnExtensionInstance( self._version, payload, @@ -141,22 +171,46 @@ def fetch(self) -> AvailableAddOnExtensionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AvailableAddOnExtensionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + Fetch the AvailableAddOnExtensionInstance and return response metadata - :returns: The fetched AvailableAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() return AvailableAddOnExtensionInstance( self._version, payload, @@ -164,6 +218,22 @@ async def fetch_async(self) -> AvailableAddOnExtensionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -184,6 +254,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstan :param payload: Payload response from the API """ + return AvailableAddOnExtensionInstance( self._version, payload, @@ -269,6 +340,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -288,6 +409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -314,6 +436,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -322,6 +445,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -353,7 +526,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -386,7 +561,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: """ @@ -398,7 +649,9 @@ def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: :returns: Page of AvailableAddOnExtensionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: """ @@ -410,7 +663,9 @@ async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: :returns: Page of AvailableAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> AvailableAddOnExtensionContext: """ diff --git a/twilio/rest/marketplace/v1/installed_add_on/__init__.py b/twilio/rest/marketplace/v1/installed_add_on/__init__.py index 8fedfb9b41..2553e78bf8 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/__init__.py +++ b/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnContext] = None @property @@ -100,6 +102,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InstalledAddOnInstance": """ Fetch the InstalledAddOnInstance @@ -118,6 +138,24 @@ async def fetch_async(self) -> "InstalledAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration: Union[object, object] = values.unset, @@ -154,6 +192,42 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration=configuration, + unique_name=unique_name, + ) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -198,6 +272,20 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[InstalledAddOnExtensionList] = None self._usage: Optional[InstalledAddOnUsageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InstalledAddOnInstance @@ -205,10 +293,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -217,67 +327,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InstalledAddOnInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InstalledAddOnInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = self._fetch() return InstalledAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> InstalledAddOnInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InstalledAddOnInstance + Fetch the InstalledAddOnInstance and return response metadata - :returns: The fetched InstalledAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = await self._fetch_async() return InstalledAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Update the InstalledAddOnInstance - - :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + Internal helper for update operation - :returns: The updated InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -292,25 +454,60 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronous coroutine to update the InstalledAddOnInstance + Update the InstalledAddOnInstance :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. :returns: The updated InstalledAddOnInstance """ + payload, _, _ = self._update( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance and return response metadata + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -324,12 +521,49 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + payload, _, _ = await self._update_async( + configuration=configuration, unique_name=unique_name + ) return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance and return response metadata + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -372,6 +606,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: :param payload: Payload response from the API """ + return InstalledAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -396,22 +631,18 @@ def __init__(self, version: Version): self._uri = "/InstalledAddOns" - def create( + def _create( self, available_add_on_sid: str, accept_terms_of_service: bool, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Create the InstalledAddOnInstance + Internal helper for create operation - :param available_add_on_sid: The SID of the AvaliableAddOn to install. - :param accept_terms_of_service: Whether the Terms of Service were accepted. - :param configuration: The JSON object that represents the configuration of the new Add-on being installed. - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. - - :returns: The created InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -430,13 +661,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InstalledAddOnInstance(self._version, payload) - - async def create_async( + def create( self, available_add_on_sid: str, accept_terms_of_service: bool, @@ -444,7 +673,7 @@ async def create_async( unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronously create the InstalledAddOnInstance + Create the InstalledAddOnInstance :param available_add_on_sid: The SID of the AvaliableAddOn to install. :param accept_terms_of_service: Whether the Terms of Service were accepted. @@ -453,6 +682,53 @@ async def create_async( :returns: The created InstalledAddOnInstance """ + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -470,12 +746,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + payload, _, _ = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) return InstalledAddOnInstance(self._version, payload) + async def create_with_http_info_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -526,6 +851,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -545,6 +920,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -571,6 +947,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -579,6 +956,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -645,6 +1072,76 @@ async def page_async( ) return InstalledAddOnPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InstalledAddOnPage: """ Retrieve a specific page of InstalledAddOnInstance records from the API. diff --git a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py index 88f160ed29..844c78e33f 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "installed_add_on_sid": installed_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnExtensionContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "InstalledAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": """ Update the InstalledAddOnExtensionInstance @@ -113,6 +133,30 @@ async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance" enabled=enabled, ) + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,20 +190,30 @@ def __init__(self, version: Version, installed_add_on_sid: str, sid: str): **self._solution ) - def fetch(self) -> InstalledAddOnExtensionInstance: + def _fetch(self) -> tuple: """ - Fetch the InstalledAddOnExtensionInstance - + Internal helper for fetch operation - :returns: The fetched InstalledAddOnExtensionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = self._fetch() return InstalledAddOnExtensionInstance( self._version, payload, @@ -167,22 +221,46 @@ def fetch(self) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InstalledAddOnExtensionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + Fetch the InstalledAddOnExtensionInstance and return response metadata - :returns: The fetched InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() return InstalledAddOnExtensionInstance( self._version, payload, @@ -190,13 +268,28 @@ async def fetch_async(self) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the InstalledAddOnExtensionInstance + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance and return response metadata - :param enabled: Whether the Extension should be invoked. - :returns: The updated InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, enabled: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -210,10 +303,19 @@ def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + payload, _, _ = self._update(enabled=enabled) return InstalledAddOnExtensionInstance( self._version, payload, @@ -221,13 +323,29 @@ def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + def update_with_http_info(self, enabled: bool) -> ApiResponse: """ - Asynchronous coroutine to update the InstalledAddOnExtensionInstance + Update the InstalledAddOnExtensionInstance and return response metadata :param enabled: Whether the Extension should be invoked. - :returns: The updated InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, enabled: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -241,10 +359,19 @@ async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + payload, _, _ = await self._update_async(enabled=enabled) return InstalledAddOnExtensionInstance( self._version, payload, @@ -252,6 +379,23 @@ async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance and return response metadata + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -272,6 +416,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstan :param payload: Payload response from the API """ + return InstalledAddOnExtensionInstance( self._version, payload, @@ -357,6 +502,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -376,6 +571,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -402,6 +598,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -410,6 +607,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -441,7 +688,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -474,7 +723,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: """ @@ -486,7 +811,9 @@ def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: :returns: Page of InstalledAddOnExtensionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: """ @@ -498,7 +825,9 @@ async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: :returns: Page of InstalledAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> InstalledAddOnExtensionContext: """ diff --git a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py index 1a54756496..9a2a66844b 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -167,16 +168,15 @@ def __init__(self, version: Version, installed_add_on_sid: str): **self._solution ) - def create( + def _create( self, marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, - ) -> InstalledAddOnUsageInstance: + ) -> tuple: """ - Create the InstalledAddOnUsageInstance - - :param marketplace_v1_installed_add_on_installed_add_on_usage: + Internal helper for create operation - :returns: The created InstalledAddOnUsageInstance + Returns: + tuple: (payload, status_code, headers) """ data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() @@ -186,26 +186,60 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + payload, _, _ = self._create( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) return InstalledAddOnUsageInstance( self._version, payload, installed_add_on_sid=self._solution["installed_add_on_sid"], ) - async def create_async( + def create_with_http_info( self, marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, - ) -> InstalledAddOnUsageInstance: + ) -> ApiResponse: """ - Asynchronously create the InstalledAddOnUsageInstance + Create the InstalledAddOnUsageInstance and return response metadata :param marketplace_v1_installed_add_on_installed_add_on_usage: - :returns: The created InstalledAddOnUsageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + instance = InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() @@ -215,16 +249,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Asynchronously create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + payload, _, _ = await self._create_async( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) return InstalledAddOnUsageInstance( self._version, payload, installed_add_on_sid=self._solution["installed_add_on_sid"], ) + async def create_with_http_info_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnUsageInstance and return response metadata + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + marketplace_v1_installed_add_on_installed_add_on_usage=marketplace_v1_installed_add_on_installed_add_on_usage + ) + instance = InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/marketplace/v1/module_data.py b/twilio/rest/marketplace/v1/module_data.py index 1308c17a91..90a6cbb99a 100644 --- a/twilio/rest/marketplace/v1/module_data.py +++ b/twilio/rest/marketplace/v1/module_data.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,18 +72,16 @@ def __init__(self, version: Version): self._uri = "/Listings" - def create( + def _create( self, module_info: Union[str, object] = values.unset, configuration: Union[str, object] = values.unset, - ) -> ModuleDataInstance: + ) -> tuple: """ - Create the ModuleDataInstance - - :param module_info: A JSON object containing essential attributes that define a Listing. - :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + Internal helper for create operation - :returns: The created ModuleDataInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -97,25 +96,58 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ModuleDataInstance(self._version, payload) - - async def create_async( + def create( self, module_info: Union[str, object] = values.unset, configuration: Union[str, object] = values.unset, ) -> ModuleDataInstance: """ - Asynchronously create the ModuleDataInstance + Create the ModuleDataInstance :param module_info: A JSON object containing essential attributes that define a Listing. :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. :returns: The created ModuleDataInstance """ + payload, _, _ = self._create( + module_info=module_info, configuration=configuration + ) + return ModuleDataInstance(self._version, payload) + + def create_with_http_info( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ModuleDataInstance and return response metadata + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + module_info=module_info, configuration=configuration + ) + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -129,44 +161,119 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ModuleDataInstance: + """ + Asynchronously create the ModuleDataInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: The created ModuleDataInstance + """ + payload, _, _ = await self._create_async( + module_info=module_info, configuration=configuration + ) return ModuleDataInstance(self._version, payload) - def fetch(self) -> ModuleDataInstance: + async def create_with_http_info_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously fetch the ModuleDataInstance + Asynchronously create the ModuleDataInstance and return response metadata + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. - :returns: The fetched ModuleDataInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + module_info=module_info, configuration=configuration + ) + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ModuleDataInstance: + """ + Fetch the ModuleDataInstance + + :returns: The fetched ModuleDataInstance + """ + payload, _, _ = self._fetch() return ModuleDataInstance(self._version, payload) - async def fetch_async(self) -> ModuleDataInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the ModuleDataInstance + Fetch the ModuleDataInstance and return response metadata - :returns: The fetched ModuleDataInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + payload, _, _ = await self._fetch_async() return ModuleDataInstance(self._version, payload) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the ModuleDataInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ModuleDataInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/marketplace/v1/module_data_management.py b/twilio/rest/marketplace/v1/module_data_management.py index 6ed82d846d..6ac9e02d46 100644 --- a/twilio/rest/marketplace/v1/module_data_management.py +++ b/twilio/rest/marketplace/v1/module_data_management.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ModuleDataManagementContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "ModuleDataManagementInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, module_info: Union[str, object] = values.unset, @@ -154,6 +174,72 @@ async def update_async( pricing=pricing, ) + def update_with_http_info( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ModuleDataManagementInstance with HTTP info + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + async def update_with_http_info_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance with HTTP info + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,49 +267,97 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Listing/{sid}".format(**self._solution) - def fetch(self) -> ModuleDataManagementInstance: + def _fetch(self) -> tuple: """ - Fetch the ModuleDataManagementInstance - + Internal helper for fetch operation - :returns: The fetched ModuleDataManagementInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ModuleDataManagementInstance: + """ + Fetch the ModuleDataManagementInstance + + :returns: The fetched ModuleDataManagementInstance + """ + payload, _, _ = self._fetch() return ModuleDataManagementInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ModuleDataManagementInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ModuleDataManagementInstance + Fetch the ModuleDataManagementInstance and return response metadata - :returns: The fetched ModuleDataManagementInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + payload, _, _ = await self._fetch_async() return ModuleDataManagementInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, module_info: Union[str, object] = values.unset, description: Union[str, object] = values.unset, @@ -232,19 +366,12 @@ def update( support: Union[str, object] = values.unset, configuration: Union[str, object] = values.unset, pricing: Union[str, object] = values.unset, - ) -> ModuleDataManagementInstance: + ) -> tuple: """ - Update the ModuleDataManagementInstance - - :param module_info: A JSON object containing essential attributes that define a Listing. - :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. - :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. - :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. - :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. - :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. - :param pricing: A JSON object for providing Listing's purchase options. + Internal helper for update operation - :returns: The updated ModuleDataManagementInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,15 +391,47 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + payload, _, _ = self._update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) return ModuleDataManagementInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, module_info: Union[str, object] = values.unset, description: Union[str, object] = values.unset, @@ -281,9 +440,9 @@ async def update_async( support: Union[str, object] = values.unset, configuration: Union[str, object] = values.unset, pricing: Union[str, object] = values.unset, - ) -> ModuleDataManagementInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ModuleDataManagementInstance + Update the ModuleDataManagementInstance and return response metadata :param module_info: A JSON object containing essential attributes that define a Listing. :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. @@ -293,7 +452,37 @@ async def update_async( :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. :param pricing: A JSON object for providing Listing's purchase options. - :returns: The updated ModuleDataManagementInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + instance = ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -313,14 +502,83 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + payload, _, _ = await self._update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) return ModuleDataManagementInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance and return response metadata + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + instance = ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/marketplace/v1/referral_conversion.py b/twilio/rest/marketplace/v1/referral_conversion.py index 9d9f3c2fa9..1234b45c6f 100644 --- a/twilio/rest/marketplace/v1/referral_conversion.py +++ b/twilio/rest/marketplace/v1/referral_conversion.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,15 +87,14 @@ def __init__(self, version: Version): self._uri = "/ReferralConversion" - def create( + def _create( self, create_referral_conversion_request: CreateReferralConversionRequest - ) -> ReferralConversionInstance: + ) -> tuple: """ - Create the ReferralConversionInstance + Internal helper for create operation - :param create_referral_conversion_request: - - :returns: The created ReferralConversionInstance + Returns: + tuple: (payload, status_code, headers) """ data = create_referral_conversion_request.to_dict() @@ -104,22 +104,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ReferralConversionInstance(self._version, payload) - - async def create_async( + def create( self, create_referral_conversion_request: CreateReferralConversionRequest ) -> ReferralConversionInstance: """ - Asynchronously create the ReferralConversionInstance + Create the ReferralConversionInstance :param create_referral_conversion_request: :returns: The created ReferralConversionInstance """ + payload, _, _ = self._create( + create_referral_conversion_request=create_referral_conversion_request + ) + return ReferralConversionInstance(self._version, payload) + + def create_with_http_info( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ApiResponse: + """ + Create the ReferralConversionInstance and return response metadata + + :param create_referral_conversion_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_referral_conversion_request=create_referral_conversion_request + ) + instance = ReferralConversionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = create_referral_conversion_request.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -128,12 +156,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Asynchronously create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + payload, _, _ = await self._create_async( + create_referral_conversion_request=create_referral_conversion_request + ) return ReferralConversionInstance(self._version, payload) + async def create_with_http_info_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ApiResponse: + """ + Asynchronously create the ReferralConversionInstance and return response metadata + + :param create_referral_conversion_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_referral_conversion_request=create_referral_conversion_request + ) + instance = ReferralConversionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/assistants/AssistantsBase.py b/twilio/rest/memory/MemoryBase.py similarity index 75% rename from twilio/rest/assistants/AssistantsBase.py rename to twilio/rest/memory/MemoryBase.py index a9c9e9afcd..1ced0e0da8 100644 --- a/twilio/rest/assistants/AssistantsBase.py +++ b/twilio/rest/memory/MemoryBase.py @@ -13,24 +13,24 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.assistants.v1 import V1 +from twilio.rest.memory.v1 import V1 -class AssistantsBase(Domain): +class MemoryBase(Domain): def __init__(self, twilio: Client): """ - Initialize the Assistants Domain + Initialize the Memory Domain - :returns: Domain for Assistants + :returns: Domain for Memory """ - super().__init__(twilio, "https://assistants.twilio.com") + super().__init__(twilio, "https://memory.twilio.com") self._v1: Optional[V1] = None @property def v1(self) -> V1: """ - :returns: Versions v1 of Assistants + :returns: Versions v1 of Memory """ if self._v1 is None: self._v1 = V1(self) @@ -41,4 +41,4 @@ def __repr__(self) -> str: Provide a friendly representation :returns: Machine friendly representation """ - return "<Twilio.Assistants>" + return "<Twilio.Memory>" diff --git a/twilio/rest/memory/__init__.py b/twilio/rest/memory/__init__.py new file mode 100644 index 0000000000..3a4eec065e --- /dev/null +++ b/twilio/rest/memory/__init__.py @@ -0,0 +1,5 @@ +from twilio.rest.memory.MemoryBase import MemoryBase + + +class Memory(MemoryBase): + pass diff --git a/twilio/rest/memory/v1/__init__.py b/twilio/rest/memory/v1/__init__.py new file mode 100644 index 0000000000..3f312e4706 --- /dev/null +++ b/twilio/rest/memory/v1/__init__.py @@ -0,0 +1,272 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.memory.v1.bulk import BulkList +from twilio.rest.memory.v1.conversation_summary import ConversationSummaryList +from twilio.rest.memory.v1.data_mapping import DataMappingList +from twilio.rest.memory.v1.identifier import IdentifierList +from twilio.rest.memory.v1.identity_resolution_setting import ( + IdentityResolutionSettingList, +) +from twilio.rest.memory.v1.import_ import ImportList +from twilio.rest.memory.v1.lookup import LookupList +from twilio.rest.memory.v1.observation import ObservationList +from twilio.rest.memory.v1.operation import OperationList +from twilio.rest.memory.v1.profile import ProfileList +from twilio.rest.memory.v1.recall import RecallList +from twilio.rest.memory.v1.revision import RevisionList +from twilio.rest.memory.v1.store import StoreList +from twilio.rest.memory.v1.trait import TraitList +from twilio.rest.memory.v1.trait_group import TraitGroupList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Memory + + :param domain: The Twilio.memory domain + """ + super().__init__(domain, "v1") + self._operations: Optional[OperationList] = None + self._stores: Optional[StoreList] = None + + def bulk(self, store_id: str, bulk_id: str = None): + """ + Access the BulkList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param bulk_id: Optional instance ID to directly access BulkContext + :returns: BulkList instance if bulk_id is None, otherwise BulkContext + """ + list_instance = BulkList(self, store_id) + if bulk_id is not None: + return list_instance(bulk_id) + return list_instance + + def conversation_summaries( + self, store_id: str, profile_id: str, conversation_summary_id: str = None + ): + """ + Access the ConversationSummaryList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param conversation_summary_id: Optional instance ID to directly access ConversationSummaryContext + :returns: ConversationSummaryList instance if conversation_summary_id is None, otherwise ConversationSummaryContext + """ + list_instance = ConversationSummaryList(self, store_id, profile_id) + if conversation_summary_id is not None: + return list_instance(conversation_summary_id) + return list_instance + + def data_mappings(self, store_id: str, data_mapping_id: str = None): + """ + Access the DataMappingList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param data_mapping_id: Optional instance ID to directly access DataMappingContext + :returns: DataMappingList instance if data_mapping_id is None, otherwise DataMappingContext + """ + list_instance = DataMappingList(self, store_id) + if data_mapping_id is not None: + return list_instance(data_mapping_id) + return list_instance + + def identifiers(self, store_id: str, profile_id: str, identifier_id: str = None): + """ + Access the IdentifierList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param identifier_id: Optional instance ID to directly access IdentifierContext + :returns: IdentifierList instance if identifier_id is None, otherwise IdentifierContext + """ + list_instance = IdentifierList(self, store_id, profile_id) + if identifier_id is not None: + return list_instance(identifier_id) + return list_instance + + def identity_resolution_settings( + self, store_id: str, identity_resolution_setting_id: str = None + ): + """ + Access the IdentityResolutionSettingList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param identity_resolution_setting_id: Optional instance ID to directly access IdentityResolutionSettingContext + :returns: IdentityResolutionSettingList instance if identity_resolution_setting_id is None, otherwise IdentityResolutionSettingContext + """ + list_instance = IdentityResolutionSettingList(self, store_id) + if identity_resolution_setting_id is not None: + return list_instance(identity_resolution_setting_id) + return list_instance + + def imports(self, store_id: str, import_id: str = None): + """ + Access the ImportList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param import_id: Optional instance ID to directly access ImportContext + :returns: ImportList instance if import_id is None, otherwise ImportContext + """ + list_instance = ImportList(self, store_id) + if import_id is not None: + return list_instance(import_id) + return list_instance + + def lookup(self, store_id: str, lookup_id: str = None): + """ + Access the LookupList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param lookup_id: Optional instance ID to directly access LookupContext + :returns: LookupList instance if lookup_id is None, otherwise LookupContext + """ + list_instance = LookupList(self, store_id) + if lookup_id is not None: + return list_instance(lookup_id) + return list_instance + + def observations(self, store_id: str, profile_id: str, observation_id: str = None): + """ + Access the ObservationList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param observation_id: Optional instance ID to directly access ObservationContext + :returns: ObservationList instance if observation_id is None, otherwise ObservationContext + """ + list_instance = ObservationList(self, store_id, profile_id) + if observation_id is not None: + return list_instance(observation_id) + return list_instance + + @property + def operations(self) -> OperationList: + if self._operations is None: + self._operations = OperationList(self) + return self._operations + + def profiles(self, store_id: str, profile_id: str = None): + """ + Access the ProfileList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: Optional instance ID to directly access ProfileContext + :returns: ProfileList instance if profile_id is None, otherwise ProfileContext + """ + list_instance = ProfileList(self, store_id) + if profile_id is not None: + return list_instance(profile_id) + return list_instance + + def recall(self, store_id: str, profile_id: str, recall_id: str = None): + """ + Access the RecallList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param recall_id: Optional instance ID to directly access RecallContext + :returns: RecallList instance if recall_id is None, otherwise RecallContext + """ + list_instance = RecallList(self, store_id, profile_id) + if recall_id is not None: + return list_instance(recall_id) + return list_instance + + def revisions( + self, + store_id: str, + profile_id: str, + observation_id: str, + revision_id: str = None, + ): + """ + Access the RevisionList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param observation_id: The observation ID. + + :param revision_id: Optional instance ID to directly access RevisionContext + :returns: RevisionList instance if revision_id is None, otherwise RevisionContext + """ + list_instance = RevisionList(self, store_id, profile_id, observation_id) + if revision_id is not None: + return list_instance(revision_id) + return list_instance + + @property + def stores(self) -> StoreList: + if self._stores is None: + self._stores = StoreList(self) + return self._stores + + def traits(self, store_id: str, profile_id: str, trait_id: str = None): + """ + Access the TraitList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + :param trait_id: Optional instance ID to directly access TraitContext + :returns: TraitList instance if trait_id is None, otherwise TraitContext + """ + list_instance = TraitList(self, store_id, profile_id) + if trait_id is not None: + return list_instance(trait_id) + return list_instance + + def trait_groups(self, store_id: str, trait_group_id: str = None): + """ + Access the TraitGroupList resource + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + :param trait_group_id: Optional instance ID to directly access TraitGroupContext + :returns: TraitGroupList instance if trait_group_id is None, otherwise TraitGroupContext + """ + list_instance = TraitGroupList(self, store_id) + if trait_group_id is not None: + return list_instance(trait_group_id) + return list_instance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1>" diff --git a/twilio/rest/memory/v1/bulk.py b/twilio/rest/memory/v1/bulk.py new file mode 100644 index 0000000000..eb77945844 --- /dev/null +++ b/twilio/rest/memory/v1/bulk.py @@ -0,0 +1,216 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkInstance(InstanceResource): + """ + :ivar message: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], store_id: str): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.BulkInstance {}>".format(context) + + +class BulkList(ListResource): + + class ProfileData(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + class UpdateProfilesBulkRequest(object): + """ + :ivar profiles: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profiles: Optional[List[BulkList.ProfileData]] = payload.get( + "profiles" + ) + + def to_dict(self): + return { + "profiles": ( + [profiles.to_dict() for profiles in self.profiles] + if self.profiles is not None + else None + ), + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the BulkList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Bulk".format(**self._solution) + + def _update(self, update_profiles_bulk_request: UpdateProfilesBulkRequest) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_profiles_bulk_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> BulkInstance: + """ + Update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + payload, _, _ = self._update( + update_profiles_bulk_request=update_profiles_bulk_request + ) + return BulkInstance(self._version, payload, store_id=self._solution["store_id"]) + + def update_with_http_info( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Update the BulkInstance and return response metadata + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + update_profiles_bulk_request=update_profiles_bulk_request + ) + instance = BulkInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = update_profiles_bulk_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> BulkInstance: + """ + Asynchronously update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + payload, _, _ = await self._update_async( + update_profiles_bulk_request=update_profiles_bulk_request + ) + return BulkInstance(self._version, payload, store_id=self._solution["store_id"]) + + async def update_with_http_info_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Asynchronously update the BulkInstance and return response metadata + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + update_profiles_bulk_request=update_profiles_bulk_request + ) + instance = BulkInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.BulkList>" diff --git a/twilio/rest/memory/v1/conversation_summary.py b/twilio/rest/memory/v1/conversation_summary.py new file mode 100644 index 0000000000..7f95b1beb9 --- /dev/null +++ b/twilio/rest/memory/v1/conversation_summary.py @@ -0,0 +1,1331 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ConversationSummaryInstance(InstanceResource): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + :ivar id: A unique identifier for the summary using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the summary was created. + :ivar updated_at: The timestamp when the summary was last updated. + :ivar message: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + summary_id: Optional[str] = None, + ): + super().__init__(version) + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.conversation_id: Optional[str] = payload.get("conversationId") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.message: Optional[str] = payload.get("message") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or summary_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "summary_id": summary_id, + } + + self._context: Optional[ConversationSummaryContext] = None + + @property + def _proxy(self) -> "ConversationSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationSummaryContext for this ConversationSummaryInstance + """ + if self._context is None: + self._context = ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ConversationSummaryInstance": + """ + Fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationSummaryInstance": + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, summary_core_patch: SummaryCorePatch + ) -> "ConversationSummaryInstance": + """ + Patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + return self._proxy.patch( + summary_core_patch=summary_core_patch, + ) + + async def patch_async( + self, summary_core_patch: SummaryCorePatch + ) -> "ConversationSummaryInstance": + """ + Asynchronous coroutine to patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + return await self._proxy.patch_async( + summary_core_patch=summary_core_patch, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ConversationSummaryInstance {}>".format(context) + + +class ConversationSummaryContext(InstanceContext): + + def __init__( + self, version: Version, store_id: str, profile_id: str, summary_id: str + ): + """ + Initialize the ConversationSummaryContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param summary_id: The summary ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "summary_id": summary_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/ConversationSummaries/{summary_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationSummaryInstance: + """ + Fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + payload, _, _ = self._fetch() + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ConversationSummaryInstance: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance + + + :returns: The fetched ConversationSummaryInstance + """ + payload, _, _ = await self._fetch_async() + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationSummaryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, summary_core_patch: SummaryCorePatch) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = summary_core_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, summary_core_patch: SummaryCorePatch + ) -> ConversationSummaryInstance: + """ + Patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + payload, _, _ = self._patch(summary_core_patch=summary_core_patch) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + def patch_with_http_info(self, summary_core_patch: SummaryCorePatch) -> ApiResponse: + """ + Patch the ConversationSummaryInstance and return response metadata + + :param summary_core_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + summary_core_patch=summary_core_patch + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, summary_core_patch: SummaryCorePatch) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = summary_core_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, summary_core_patch: SummaryCorePatch + ) -> ConversationSummaryInstance: + """ + Asynchronous coroutine to patch the ConversationSummaryInstance + + :param summary_core_patch: + + :returns: The patched ConversationSummaryInstance + """ + payload, _, _ = await self._patch_async(summary_core_patch=summary_core_patch) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + + async def patch_with_http_info_async( + self, summary_core_patch: SummaryCorePatch + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ConversationSummaryInstance and return response metadata + + :param summary_core_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + summary_core_patch=summary_core_patch + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=self._solution["summary_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ConversationSummaryContext {}>".format(context) + + +class ConversationSummaryPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationSummaryInstance: + """ + Build an instance of ConversationSummaryInstance + + :param payload: Payload response from the API + """ + + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ConversationSummaryPage>" + + +class ConversationSummaryList(ListResource): + + class CreateSummariesRequest(object): + """ + :ivar summaries: Array of summaries to create in a single batch operation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.summaries: Optional[List[ConversationSummaryList.SummaryCore]] = ( + payload.get("summaries") + ) + + def to_dict(self): + return { + "summaries": ( + [summaries.to_dict() for summaries in self.summaries] + if self.summaries is not None + else None + ), + } + + class SummaryCore(object): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.conversation_id: Optional[str] = payload.get("conversationId") + + def to_dict(self): + return { + "source": self.source, + "content": self.content, + "occurredAt": self.occurred_at, + "conversationId": self.conversation_id, + } + + class SummaryCorePatch(object): + """ + :ivar source: The source system that generated the summary. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar content: The main content of the summary. + :ivar occurred_at: The timestamp when the summary was originally created. If not provided, defaults to the time the summary was received. + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.source: Optional[str] = payload.get("source") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.conversation_id: Optional[str] = payload.get("conversationId") + + def to_dict(self): + return { + "source": self.source, + "content": self.content, + "occurredAt": self.occurred_at, + "conversationId": self.conversation_id, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ConversationSummaryList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = ( + "/Stores/{store_id}/Profiles/{profile_id}/ConversationSummaries".format( + **self._solution + ) + ) + + def _create( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_summaries_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryInstance: + """ + Create the ConversationSummaryInstance + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ConversationSummaryInstance + """ + payload, _, _ = self._create( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationSummaryInstance and return response metadata + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_summaries_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryInstance: + """ + Asynchronously create the ConversationSummaryInstance + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ConversationSummaryInstance + """ + payload, _, _ = await self._create_async( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + create_summaries_request: CreateSummariesRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConversationSummaryInstance and return response metadata + + :param create_summaries_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_summaries_request=create_summaries_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ConversationSummaryInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationSummaryInstance]: + """ + Streams ConversationSummaryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationSummaryInstance]: + """ + Asynchronously streams ConversationSummaryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationSummaryInstance]: + """ + Lists ConversationSummaryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationSummaryInstance]: + """ + Asynchronously lists ConversationSummaryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConversationSummaryInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryPage: + """ + Retrieve a single page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ConversationSummaryInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationSummaryPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ConversationSummaryPage: + """ + Asynchronously retrieve a single page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ConversationSummaryInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationSummaryPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationSummaryPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConversationSummaryPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConversationSummaryPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConversationSummaryPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ConversationSummaryPage: + """ + Retrieve a specific page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationSummaryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationSummaryPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ConversationSummaryPage: + """ + Asynchronously retrieve a specific page of ConversationSummaryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationSummaryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationSummaryPage(self._version, response, solution=self._solution) + + def get(self, summary_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :param summary_id: The summary ID. + """ + return ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=summary_id, + ) + + def __call__(self, summary_id: str) -> ConversationSummaryContext: + """ + Constructs a ConversationSummaryContext + + :param summary_id: The summary ID. + """ + return ConversationSummaryContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + summary_id=summary_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ConversationSummaryList>" diff --git a/twilio/rest/memory/v1/data_mapping.py b/twilio/rest/memory/v1/data_mapping.py new file mode 100644 index 0000000000..8cefd6789e --- /dev/null +++ b/twilio/rest/memory/v1/data_mapping.py @@ -0,0 +1,1342 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class DataMappingInstance(InstanceResource): + + class DataMappingType(object): + CSV = "CSV" + DATASET = "DATASET" + + """ + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + :ivar mapping_from: + :ivar id: The unique identifier for the data mapping. + :ivar created_at: The ISO 8601 timestamp when the data mapping was created. + :ivar updated_at: The ISO 8601 timestamp when the data mapping was last updated. + :ivar version: The current version number of the DataMapping. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + data_mapping_id: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingToTraits] = payload.get("mappingTo") + self.mapping_from: Optional[DataMappingFromTypes] = payload.get("mappingFrom") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None or data_mapping_id is not None: + self._solution = { + "store_id": store_id, + "data_mapping_id": data_mapping_id, + } + + self._context: Optional[DataMappingContext] = None + + @property + def _proxy(self) -> "DataMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DataMappingContext for this DataMappingInstance + """ + if self._context is None: + self._context = DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DataMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DataMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "DataMappingInstance": + """ + Fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DataMappingInstance": + """ + Asynchronous coroutine to fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> "DataMappingInstance": + """ + Patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + return self._proxy.patch( + if_match=if_match, + data_mapping_core=data_mapping_core, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> "DataMappingInstance": + """ + Asynchronous coroutine to patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + data_mapping_core=data_mapping_core, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.DataMappingInstance {}>".format(context) + + +class DataMappingContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, data_mapping_id: str): + """ + Initialize the DataMappingContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "data_mapping_id": data_mapping_id, + } + self._uri = ( + "/ControlPlane/Stores/{store_id}/DataMappings/{data_mapping_id}".format( + **self._solution + ) + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DataMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DataMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DataMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DataMappingInstance: + """ + Fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + payload, _, _ = self._fetch() + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DataMappingInstance: + """ + Asynchronous coroutine to fetch the DataMappingInstance + + + :returns: The fetched DataMappingInstance + """ + payload, _, _ = await self._fetch_async() + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DataMappingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = data_mapping_core.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> DataMappingInstance: + """ + Patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + payload, _, _ = self._patch( + if_match=if_match, data_mapping_core=data_mapping_core + ) + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> ApiResponse: + """ + Patch the DataMappingInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, data_mapping_core=data_mapping_core + ) + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = data_mapping_core.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> DataMappingInstance: + """ + Asynchronous coroutine to patch the DataMappingInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: The patched DataMappingInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, data_mapping_core=data_mapping_core + ) + return DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data_mapping_core: Union[DataMappingCore, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the DataMappingInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param data_mapping_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, data_mapping_core=data_mapping_core + ) + instance = DataMappingInstance( + self._version, + payload, + store_id=self._solution["store_id"], + data_mapping_id=self._solution["data_mapping_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.DataMappingContext {}>".format(context) + + +class DataMappingPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> DataMappingInstance: + """ + Build an instance of DataMappingInstance + + :param payload: Payload response from the API + """ + + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.DataMappingPage>" + + +class DataMappingList(ListResource): + + class CreateDataMappingInput(object): + """ + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + :ivar mapping_from: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingList.DataMappingToTraits] = ( + payload.get("mappingTo") + ) + self.mapping_from: Optional[DataMappingList.DataMappingFromTypes] = ( + payload.get("mappingFrom") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "isEnabled": self.is_enabled, + "mappingTo": ( + self.mapping_to.to_dict() if self.mapping_to is not None else None + ), + "mappingFrom": ( + self.mapping_from.to_dict() + if self.mapping_from is not None + else None + ), + } + + class DataMappingCore(object): + """ + :ivar display_name: Name of the data mapping. + :ivar description: A human readable description of this resource, up to 512 characters. + :ivar is_enabled: Flag indicating whether the data mapping is active. When true, data will be ingested and mapped according to the configuration. When false, the data mapping will be inactive and no data will be ingested into the Memory Store. + :ivar mapping_to: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.is_enabled: Optional[bool] = payload.get("isEnabled") + self.mapping_to: Optional[DataMappingList.DataMappingToTraits] = ( + payload.get("mappingTo") + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "isEnabled": self.is_enabled, + "mappingTo": ( + self.mapping_to.to_dict() if self.mapping_to is not None else None + ), + } + + class DataMappingFromTypes(object): + """ + :ivar type: The source data type, which determines the source of the data and the required configuration parameters. + :ivar columns: The list of CSV column names that serve as the source fields. + :ivar dataset_id: The unique identifier of the TDI dataset to connect. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["DataMappingInstance.str"] = payload.get("type") + self.columns: Optional[List[str]] = payload.get("columns") + self.dataset_id: Optional[str] = payload.get("datasetId") + + def to_dict(self): + return { + "type": self.type, + "columns": self.columns, + "datasetId": self.dataset_id, + } + + class DataMappingToTraits(object): + """ + :ivar type: The destination data type, which determines where to write the data and the required configuration parameters. + :ivar mappings: The list of field to trait mappings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["DataMappingInstance.str"] = payload.get("type") + self.mappings: Optional[List[DataMappingList.MappingTraitItem]] = ( + payload.get("mappings") + ) + + def to_dict(self): + return { + "type": self.type, + "mappings": ( + [mappings.to_dict() for mappings in self.mappings] + if self.mappings is not None + else None + ), + } + + class MappingTraitItem(object): + """ + :ivar expression: The expression identifying the field/column in the source. + :ivar trait_group: The name of the Trait Group to map to. + :ivar trait_name: The name of the trait within the Trait Group to map to. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.expression: Optional[str] = payload.get("expression") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.trait_name: Optional[str] = payload.get("traitName") + + def to_dict(self): + return { + "expression": self.expression, + "traitGroup": self.trait_group, + "traitName": self.trait_name, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the DataMappingList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/DataMappings".format( + **self._solution + ) + + def _create(self, create_data_mapping_input: CreateDataMappingInput) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_data_mapping_input.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_data_mapping_input: CreateDataMappingInput + ) -> DataMappingInstance: + """ + Create the DataMappingInstance + + :param create_data_mapping_input: + + :returns: The created DataMappingInstance + """ + payload, _, _ = self._create( + create_data_mapping_input=create_data_mapping_input + ) + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, create_data_mapping_input: CreateDataMappingInput + ) -> ApiResponse: + """ + Create the DataMappingInstance and return response metadata + + :param create_data_mapping_input: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_data_mapping_input=create_data_mapping_input + ) + instance = DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_data_mapping_input.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> DataMappingInstance: + """ + Asynchronously create the DataMappingInstance + + :param create_data_mapping_input: + + :returns: The created DataMappingInstance + """ + payload, _, _ = await self._create_async( + create_data_mapping_input=create_data_mapping_input + ) + return DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, create_data_mapping_input: CreateDataMappingInput + ) -> ApiResponse: + """ + Asynchronously create the DataMappingInstance and return response metadata + + :param create_data_mapping_input: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_data_mapping_input=create_data_mapping_input + ) + instance = DataMappingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataMappingInstance]: + """ + Streams DataMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DataMappingInstance]: + """ + Asynchronously streams DataMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + type=type, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataMappingInstance]: + """ + Lists DataMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataMappingInstance]: + """ + Asynchronously lists DataMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DataMappingInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param DataMappingType type: Filter data mappings by type. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + type=type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + ) -> DataMappingPage: + """ + Retrieve a single page of DataMappingInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :returns: Page of DataMappingInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "type": type, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataMappingPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + ) -> DataMappingPage: + """ + Asynchronously retrieve a single page of DataMappingInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :returns: Page of DataMappingInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "type": type, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataMappingPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataMappingPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DataMappingPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + type: Union[DataMappingType, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param type: Filter data mappings by type. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataMappingPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DataMappingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DataMappingPage: + """ + Retrieve a specific page of DataMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DataMappingPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> DataMappingPage: + """ + Asynchronously retrieve a specific page of DataMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataMappingPage(self._version, response, solution=self._solution) + + def get(self, data_mapping_id: str) -> DataMappingContext: + """ + Constructs a DataMappingContext + + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + return DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=data_mapping_id, + ) + + def __call__(self, data_mapping_id: str) -> DataMappingContext: + """ + Constructs a DataMappingContext + + :param data_mapping_id: A unique DataMapping ID using Twilio Type ID (TTID) format + """ + return DataMappingContext( + self._version, + store_id=self._solution["store_id"], + data_mapping_id=data_mapping_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.DataMappingList>" diff --git a/twilio/rest/memory/v1/identifier.py b/twilio/rest/memory/v1/identifier.py new file mode 100644 index 0000000000..b6579a3221 --- /dev/null +++ b/twilio/rest/memory/v1/identifier.py @@ -0,0 +1,1010 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class IdentifierInstance(InstanceResource): + """ + :ivar message: + :ivar id_type: Identifier type defined in Identity Resolution Settings. + :ivar values: Server managed collection of stored values for the identifier type. Identifier values are normalized according to the corresponding identifier settings and ordered chronologically. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + id_type: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.id_type: Optional[str] = payload.get("idType") + self.values: Optional[List[str]] = payload.get("values") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or id_type is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "id_type": id_type, + } + + self._context: Optional[IdentifierContext] = None + + @property + def _proxy(self) -> "IdentifierContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IdentifierContext for this IdentifierInstance + """ + if self._context is None: + self._context = IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return self._context + + def delete(self, remove_all: Union[bool, object] = values.unset) -> bool: + """ + Deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + remove_all=remove_all, + ) + + async def delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + remove_all=remove_all, + ) + + def delete_with_http_info( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the IdentifierInstance with HTTP info + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + remove_all=remove_all, + ) + + async def delete_with_http_info_async( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IdentifierInstance with HTTP info + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + remove_all=remove_all, + ) + + def fetch(self) -> "IdentifierInstance": + """ + Fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IdentifierInstance": + """ + Asynchronous coroutine to fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentifierInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentifierInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch(self, identifier_update: IdentifierUpdate) -> "IdentifierInstance": + """ + Patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + return self._proxy.patch( + identifier_update=identifier_update, + ) + + async def patch_async( + self, identifier_update: IdentifierUpdate + ) -> "IdentifierInstance": + """ + Asynchronous coroutine to patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + return await self._proxy.patch_async( + identifier_update=identifier_update, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.IdentifierInstance {}>".format(context) + + +class IdentifierContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str, id_type: str): + """ + Initialize the IdentifierContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "id_type": id_type, + } + self._uri = ( + "/Stores/{store_id}/Profiles/{profile_id}/Identifiers/{id_type}".format( + **self._solution + ) + ) + + def _delete(self, remove_all: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "removeAll": serialize.boolean_to_string(remove_all), + } + ) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def delete(self, remove_all: Union[bool, object] = values.unset) -> bool: + """ + Deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete(remove_all=remove_all) + return success + + def delete_with_http_info( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Deletes the IdentifierInstance and return response metadata + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(remove_all=remove_all) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "removeAll": serialize.boolean_to_string(remove_all), + } + ) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + async def delete_async( + self, remove_all: Union[bool, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the IdentifierInstance + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(remove_all=remove_all) + return success + + async def delete_with_http_info_async( + self, remove_all: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IdentifierInstance and return response metadata + + :param remove_all: When true, removes every stored value for the identifier type in a single operation. Defaults to false. + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(remove_all=remove_all) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IdentifierInstance: + """ + Fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + payload, _, _ = self._fetch() + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentifierInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IdentifierInstance: + """ + Asynchronous coroutine to fetch the IdentifierInstance + + + :returns: The fetched IdentifierInstance + """ + payload, _, _ = await self._fetch_async() + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentifierInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, identifier_update: IdentifierUpdate) -> IdentifierInstance: + """ + Patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + payload, _, _ = self._patch(identifier_update=identifier_update) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + def patch_with_http_info(self, identifier_update: IdentifierUpdate) -> ApiResponse: + """ + Patch the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(identifier_update=identifier_update) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, identifier_update: IdentifierUpdate) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, identifier_update: IdentifierUpdate + ) -> IdentifierInstance: + """ + Asynchronous coroutine to patch the IdentifierInstance + + :param identifier_update: + + :returns: The patched IdentifierInstance + """ + payload, _, _ = await self._patch_async(identifier_update=identifier_update) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + + async def patch_with_http_info_async( + self, identifier_update: IdentifierUpdate + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the IdentifierInstance and return response metadata + + :param identifier_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + identifier_update=identifier_update + ) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=self._solution["id_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.IdentifierContext {}>".format(context) + + +class IdentifierPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> IdentifierInstance: + """ + Build an instance of IdentifierInstance + + :param payload: Payload response from the API + """ + + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.IdentifierPage>" + + +class IdentifierList(ListResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. + :ivar value: Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + "idType": self.id_type, + "value": self.value, + } + + class IdentifierUpdate(object): + """ + :ivar id_type: The identifier type to update (e.g., email, phone). + :ivar old_value: Existing stored value to replace. + :ivar new_value: New value to store for the identifier. Normalization rules from the corresponding identifier settings apply. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.old_value: Optional[str] = payload.get("oldValue") + self.new_value: Optional[str] = payload.get("newValue") + + def to_dict(self): + return { + "idType": self.id_type, + "oldValue": self.old_value, + "newValue": self.new_value, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the IdentifierList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Identifiers".format( + **self._solution + ) + + def _create(self, identifier: Identifier) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, identifier: Identifier) -> IdentifierInstance: + """ + Create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + payload, _, _ = self._create(identifier=identifier) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the IdentifierInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identifier=identifier) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identifier: Identifier) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, identifier: Identifier) -> IdentifierInstance: + """ + Asynchronously create the IdentifierInstance + + :param identifier: + + :returns: The created IdentifierInstance + """ + payload, _, _ = await self._create_async(identifier=identifier) + return IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronously create the IdentifierInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identifier=identifier) + instance = IdentifierInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def list( + self, + ) -> List[IdentifierInstance]: + """ + Lists IdentifierInstance records from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return [ + IdentifierInstance( + self._version, + item, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + for item in payload["identifiers"] + ] + + async def list_async( + self, + ) -> List[IdentifierInstance]: + """ + Asynchronously lists IdentifierInstance records from the API as a list. + + :returns: list that will contain up to limit results + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + data = values.of({}) + payload, _, _ = await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return [ + IdentifierInstance( + self._version, + item, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + for item in payload["identifiers"] + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IdentifierInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IdentifierInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + ) -> IdentifierPage: + """ + Retrieve a single page of IdentifierInstance records from the API. + Request is executed immediately + + :returns: Page of IdentifierInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IdentifierPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + ) -> IdentifierPage: + """ + Asynchronously retrieve a single page of IdentifierInstance records from the API. + Request is executed immediately + + :returns: Page of IdentifierInstance + """ + data = values.of({}) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IdentifierPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IdentifierPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IdentifierPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IdentifierPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IdentifierPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> IdentifierPage: + """ + Retrieve a specific page of IdentifierInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IdentifierInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IdentifierPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> IdentifierPage: + """ + Asynchronously retrieve a specific page of IdentifierInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IdentifierInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IdentifierPage(self._version, response, solution=self._solution) + + def get(self, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + return IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=id_type, + ) + + def __call__(self, id_type: str) -> IdentifierContext: + """ + Constructs a IdentifierContext + + :param id_type: Identifier type configured for the service (for example `email`, `phone`, or `externalId`). + """ + return IdentifierContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + id_type=id_type, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.IdentifierList>" diff --git a/twilio/rest/memory/v1/identity_resolution_setting.py b/twilio/rest/memory/v1/identity_resolution_setting.py new file mode 100644 index 0000000000..6c1ea44397 --- /dev/null +++ b/twilio/rest/memory/v1/identity_resolution_setting.py @@ -0,0 +1,366 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class IdentityResolutionSettingInstance(InstanceResource): + """ + :ivar identifier_configs: List of identifier types and their resolution settings. + :ivar matching_rules: Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Individual rules are evaluated with `OR` logic between them, meaning that satisfying any single rule will trigger a match. Each rule is a single identifier type; compound rules are not supported. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + :ivar version: The current version number of the Identity Resolution Settings. Incremented on each successful update. + :ivar message: + :ivar status_url: URI to check operation status. + """ + + def __init__(self, version: Version, payload: ResponseResource, store_id: str): + super().__init__(version) + + self.identifier_configs: Optional[List[str]] = payload.get("identifierConfigs") + self.matching_rules: Optional[List[str]] = payload.get("matchingRules") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.IdentityResolutionSettingInstance {}>".format(context) + + +class IdentityResolutionSettingList(ListResource): + + class IdentifierConfig(object): + """ + :ivar id_type: Name of the identifier type. Usual values are email, phone, external_id etc. + :ivar matching_algo: The algorithm to use for matching identifier values. - `exact`, exact string match. - `fuzzy`, low precision match allowing for some variations. + :ivar matching_threshold: The `fuzzy` matching threshold percentage. + :ivar limit: Maximum number of historical values to retain. + :ivar limit_policy: Removal policy to apply when the number of values exceeds the limit and is based on the timestamp of the request when the identifier was added. - `fifo`: First In First Out, removes the oldest values first. - `lifo`: Last In First Out, removes the most recent values first. + :ivar enforce_unique: When enabled, more than one profile may not share the same identifier value. Adding a shared identifier to a second profile may trigger a merge. Disabling creates a compound identifier where merges are only triggered if two or more identifiers satisfy a matching rule. + :ivar normalization: Normalization to apply to the identifier value before storing and matching. - `phone`: Normalize phone numbers to E.164 format. - `email`: Normalize email addresses by coverting to lowercase and removing spaces. - `trim`: Removes spaces from both ends of the string. - `none`: No normalization. **Important Note for Phone Number Normalization:** When using the `phone` normalization option, please adhere to the following guidelines to ensure proper formatting: - All US numbers must be at least valid 10 digit phone numbers with area code. They may also include or omit the \"+1\" prefix. - Non-US numbers must include a 1-3 digit country code (a \"+\" prefix is optional). Non-US national formats are not supported and will be interpreted as US numbers. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.matching_algo: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("matchingAlgo") + ) + self.matching_threshold: Optional[int] = payload.get("matchingThreshold") + self.limit: Optional[int] = payload.get("limit") + self.limit_policy: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("limitPolicy") + ) + self.enforce_unique: Optional[bool] = payload.get("enforceUnique") + self.normalization: Optional["IdentityResolutionSettingInstance.str"] = ( + payload.get("normalization") + ) + + def to_dict(self): + return { + "idType": self.id_type, + "matchingAlgo": self.matching_algo, + "matchingThreshold": self.matching_threshold, + "limit": self.limit, + "limitPolicy": self.limit_policy, + "enforceUnique": self.enforce_unique, + "normalization": self.normalization, + } + + class IdentityResolutionSettingsCore(object): + """ + :ivar identifier_configs: List of identifier types and their resolution settings. + :ivar matching_rules: Priority list of identifiers to locate profiles to apply new data to, or for determining if two existing profiles should merge. Individual rules are evaluated with `OR` logic between them, meaning that satisfying any single rule will trigger a match. Each rule is a single identifier type; compound rules are not supported. Rules are evaluated in order. - If no rule matches against existing profiles, a new profile will be created. - If a rule matches to a single existing profile, the profile will be updated. - If a rule matches to multiple existing profiles, those existing profiles will be merged. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identifier_configs: Optional[ + List[IdentityResolutionSettingList.IdentifierConfig] + ] = payload.get("identifierConfigs") + self.matching_rules: Optional[List[str]] = payload.get("matchingRules") + + def to_dict(self): + return { + "identifierConfigs": ( + [ + identifier_configs.to_dict() + for identifier_configs in self.identifier_configs + ] + if self.identifier_configs is not None + else None + ), + "matchingRules": self.matching_rules, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the IdentityResolutionSettingList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/IdentityResolutionSettings".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IdentityResolutionSettingInstance: + """ + Fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + payload, _, _ = self._fetch() + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentityResolutionSettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> IdentityResolutionSettingInstance: + """ + Asynchronously fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + payload, _, _ = await self._fetch_async() + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the IdentityResolutionSettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identity_resolution_settings_core.to_dict() + + headers = values.of( + {"If-Match": if_match, "Content-Type": "application/x-www-form-urlencoded"} + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> IdentityResolutionSettingInstance: + """ + Update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = self._update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def update_with_http_info( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the IdentityResolutionSettingInstance and return response metadata + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identity_resolution_settings_core.to_dict() + + headers = values.of( + {"If-Match": if_match, "Content-Type": "application/x-www-form-urlencoded"} + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> IdentityResolutionSettingInstance: + """ + Asynchronously update the IdentityResolutionSettingInstance + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: The updated IdentityResolutionSettingInstance + """ + payload, _, _ = await self._update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + return IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def update_with_http_info_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously update the IdentityResolutionSettingInstance and return response metadata + + :param identity_resolution_settings_core: + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + instance = IdentityResolutionSettingInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.IdentityResolutionSettingList>" diff --git a/twilio/rest/memory/v1/import_.py b/twilio/rest/memory/v1/import_.py new file mode 100644 index 0000000000..3c30af4c5c --- /dev/null +++ b/twilio/rest/memory/v1/import_.py @@ -0,0 +1,958 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ImportInstance(InstanceResource): + """ + :ivar status: Current processing status of the import task + :ivar filename: Original filename of the uploaded CSV + :ivar created_at: Timestamp when the import was created + :ivar updated_at: Timestamp when the import was last updated + :ivar file_size: Size of the uploaded file in bytes (1 byte to 100 MiB) + :ivar column_mappings: Mappings of CSV header columns to traits' fields + :ivar summary: + :ivar imports: + :ivar meta: + :ivar import_id: ID of the import task. + :ivar url: Pre-signed URL to upload the CSV via a single PUT request. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + import_id: Optional[str] = None, + ): + super().__init__(version) + + self.status: Optional["ImportInstance.str"] = payload.get("status") + self.filename: Optional[str] = payload.get("filename") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + self.file_size: Optional[int] = deserialize.integer(payload.get("fileSize")) + self.column_mappings: Optional[List[ColumnMappingItem]] = payload.get( + "columnMappings" + ) + self.summary: Optional[FetchProfileImportV2200ResponseSummary] = payload.get( + "summary" + ) + self.imports: Optional[List[str]] = payload.get("imports") + self.meta: Optional[ListProfileImportsV2200ResponseMeta] = payload.get("meta") + self.import_id: Optional[str] = payload.get("importId") + self.url: Optional[str] = payload.get("url") + + # Only set _solution if path params are provided (not None) + if store_id is not None or import_id is not None: + self._solution = { + "store_id": store_id, + "import_id": import_id, + } + + self._context: Optional[ImportContext] = None + + @property + def _proxy(self) -> "ImportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ImportContext for this ImportInstance + """ + if self._context is None: + self._context = ImportContext( + self._version, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return self._context + + def fetch(self) -> "ImportInstance": + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ImportInstance": + """ + Asynchronous coroutine to fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ImportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ImportInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ImportInstance {}>".format(context) + + +class ImportContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, import_id: str): + """ + Initialize the ImportContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param import_id: The task identifier for the import process. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "import_id": import_id, + } + self._uri = "/Stores/{store_id}/Profiles/Imports/{import_id}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ImportInstance: + """ + Fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = self._fetch() + return ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ImportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ImportInstance: + """ + Asynchronous coroutine to fetch the ImportInstance + + + :returns: The fetched ImportInstance + """ + payload, _, _ = await self._fetch_async() + return ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ImportInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ImportInstance( + self._version, + payload, + store_id=self._solution["store_id"], + import_id=self._solution["import_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ImportContext {}>".format(context) + + +class ImportPage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ImportPage>" + + +class ImportList(ListResource): + + class ColumnMappingItem(object): + """ + :ivar column_name: The name of the column in the CSV header + :ivar trait_group: The trait group to which this trait belongs + :ivar trait_name: The name of the trait in the trait group + """ + + def __init__(self, payload: Dict[str, Any]): + + self.column_name: Optional[str] = payload.get("columnName") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.trait_name: Optional[str] = payload.get("traitName") + + def to_dict(self): + return { + "columnName": self.column_name, + "traitGroup": self.trait_group, + "traitName": self.trait_name, + } + + class CreateProfilesImportV2Request(object): + """ + :ivar filename: The name of the file to generate a presigned URL + :ivar file_size: The size of the file in bytes (1 byte to 100 MiB) + :ivar column_mappings: Mappings of CSV header columns to traits' fields + """ + + def __init__(self, payload: Dict[str, Any]): + + self.filename: Optional[str] = payload.get("filename") + self.file_size: Optional[int] = payload.get("fileSize") + self.column_mappings: Optional[List[ImportList.ColumnMappingItem]] = ( + payload.get("columnMappings") + ) + + def to_dict(self): + return { + "filename": self.filename, + "fileSize": self.file_size, + "columnMappings": ( + [ + column_mappings.to_dict() + for column_mappings in self.column_mappings + ] + if self.column_mappings is not None + else None + ), + } + + class FetchProfileImportV2200ResponseSummary(object): + """ + :ivar errors: Total count of errors encountered during import + :ivar warnings: Total count of warnings encountered during import + """ + + def __init__(self, payload: Dict[str, Any]): + + self.errors: Optional[int] = payload.get("errors") + self.warnings: Optional[int] = payload.get("warnings") + + def to_dict(self): + return { + "errors": self.errors, + "warnings": self.warnings, + } + + class ListProfileImportsV2200ResponseMeta(object): + """ + :ivar key: + :ivar page_size: + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[object] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the ImportList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Imports".format(**self._solution) + + def _create( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_v2_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ImportInstance: + """ + Create the ImportInstance + + :param create_profiles_import_v2_request: + + :returns: The created ImportInstance + """ + payload, _, _ = self._create( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + return ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ApiResponse: + """ + Create the ImportInstance and return response metadata + + :param create_profiles_import_v2_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + instance = ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_profiles_import_v2_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ImportInstance: + """ + Asynchronously create the ImportInstance + + :param create_profiles_import_v2_request: + + :returns: The created ImportInstance + """ + payload, _, _ = await self._create_async( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + return ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, create_profiles_import_v2_request: CreateProfilesImportV2Request + ) -> ApiResponse: + """ + Asynchronously create the ImportInstance and return response metadata + + :param create_profiles_import_v2_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_profiles_import_v2_request=create_profiles_import_v2_request + ) + instance = ImportInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ImportInstance]: + """ + Streams ImportInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ImportInstance]: + """ + Asynchronously streams ImportInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ImportInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ImportInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Lists ImportInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously lists ImportInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ImportInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ImportInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ImportPage: + """ + Retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ImportInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ImportPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ImportPage: + """ + Asynchronously retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ImportInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ImportPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ImportPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ImportPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ImportPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ImportPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ImportPage: + """ + Retrieve a specific page of ImportInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ImportInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ImportPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ImportPage: + """ + Asynchronously retrieve a specific page of ImportInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ImportInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ImportPage(self._version, response, solution=self._solution) + + def get(self, import_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param import_id: The task identifier for the import process. + """ + return ImportContext( + self._version, store_id=self._solution["store_id"], import_id=import_id + ) + + def __call__(self, import_id: str) -> ImportContext: + """ + Constructs a ImportContext + + :param import_id: The task identifier for the import process. + """ + return ImportContext( + self._version, store_id=self._solution["store_id"], import_id=import_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ImportList>" diff --git a/twilio/rest/memory/v1/lookup.py b/twilio/rest/memory/v1/lookup.py new file mode 100644 index 0000000000..f14fc0fac0 --- /dev/null +++ b/twilio/rest/memory/v1/lookup.py @@ -0,0 +1,187 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LookupInstance(InstanceResource): + """ + :ivar normalized_value: Identifier value after normalization that was used for the lookup. + :ivar profiles: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], store_id: str): + super().__init__(version) + + self.normalized_value: Optional[str] = payload.get("normalizedValue") + self.profiles: Optional[List[str]] = payload.get("profiles") + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.LookupInstance {}>".format(context) + + +class LookupList(ListResource): + + class Identifier(object): + """ + :ivar id_type: Identifier type as configured in the service's Identity Resolution Settings. + :ivar value: Raw value captured for the identifier. The service may normalize this value according to the `normalization` rule defined in the identifier settings before storage or matching (for example E.164 formatting for phone numbers). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id_type: Optional[str] = payload.get("idType") + self.value: Optional[str] = payload.get("value") + + def to_dict(self): + return { + "idType": self.id_type, + "value": self.value, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the LookupList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles/Lookup".format(**self._solution) + + def _create(self, identifier: Identifier) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, identifier: Identifier) -> LookupInstance: + """ + Create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + payload, _, _ = self._create(identifier=identifier) + return LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info(self, identifier: Identifier) -> ApiResponse: + """ + Create the LookupInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identifier=identifier) + instance = LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identifier: Identifier) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = identifier.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, identifier: Identifier) -> LookupInstance: + """ + Asynchronously create the LookupInstance + + :param identifier: + + :returns: The created LookupInstance + """ + payload, _, _ = await self._create_async(identifier=identifier) + return LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async(self, identifier: Identifier) -> ApiResponse: + """ + Asynchronously create the LookupInstance and return response metadata + + :param identifier: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identifier=identifier) + instance = LookupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.LookupList>" diff --git a/twilio/rest/memory/v1/observation.py b/twilio/rest/memory/v1/observation.py new file mode 100644 index 0000000000..3f61682c75 --- /dev/null +++ b/twilio/rest/memory/v1/observation.py @@ -0,0 +1,1467 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ObservationInstance(InstanceResource): + """ + :ivar message: + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + :ivar id: A unique identifier for the observation using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the observation was created. + :ivar updated_at: The timestamp when the observation was last updated. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + observation_id: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or observation_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + + self._context: Optional[ObservationContext] = None + + @property + def _proxy(self) -> "ObservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ObservationContext for this ObservationInstance + """ + if self._context is None: + self._context = ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ObservationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ObservationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ObservationInstance": + """ + Fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ObservationInstance": + """ + Asynchronous coroutine to fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ObservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ObservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch(self, observation_base: ObservationBase) -> "ObservationInstance": + """ + Patch the ObservationInstance + + :param observation_base: + + :returns: The patched ObservationInstance + """ + return self._proxy.patch( + observation_base=observation_base, + ) + + async def patch_async( + self, observation_base: ObservationBase + ) -> "ObservationInstance": + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_base: + + :returns: The patched ObservationInstance + """ + return await self._proxy.patch_async( + observation_base=observation_base, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ObservationInstance {}>".format(context) + + +class ObservationContext(InstanceContext): + + def __init__( + self, version: Version, store_id: str, profile_id: str, observation_id: str + ): + """ + Initialize the ObservationContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param observation_id: The observation ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations/{observation_id}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ObservationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ObservationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ObservationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ObservationInstance: + """ + Fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + payload, _, _ = self._fetch() + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ObservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ObservationInstance: + """ + Asynchronous coroutine to fetch the ObservationInstance + + + :returns: The fetched ObservationInstance + """ + payload, _, _ = await self._fetch_async() + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ObservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, observation_base: ObservationBase) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_base.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, observation_base: ObservationBase) -> ObservationInstance: + """ + Patch the ObservationInstance + + :param observation_base: + + :returns: The patched ObservationInstance + """ + payload, _, _ = self._patch(observation_base=observation_base) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def patch_with_http_info(self, observation_base: ObservationBase) -> ApiResponse: + """ + Patch the ObservationInstance and return response metadata + + :param observation_base: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(observation_base=observation_base) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, observation_base: ObservationBase) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_base.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, observation_base: ObservationBase + ) -> ObservationInstance: + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_base: + + :returns: The patched ObservationInstance + """ + payload, _, _ = await self._patch_async(observation_base=observation_base) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + async def patch_with_http_info_async( + self, observation_base: ObservationBase + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ObservationInstance and return response metadata + + :param observation_base: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + observation_base=observation_base + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ObservationContext {}>".format(context) + + +class ObservationPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> ObservationInstance: + """ + Build an instance of ObservationInstance + + :param payload: Payload response from the API + """ + + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ObservationPage>" + + +class ObservationList(ListResource): + + class CreateObservationsRequest(object): + """ + :ivar observations: Array of observations to create in a single batch operation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.observations: Optional[ + List[ObservationList.ObservationCreateRequest] + ] = payload.get("observations") + + def to_dict(self): + return { + "observations": ( + [observations.to_dict() for observations in self.observations] + if self.observations is not None + else None + ), + } + + class ObservationBase(object): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + + def to_dict(self): + return { + "content": self.content, + "occurredAt": self.occurred_at, + "source": self.source, + "conversationIds": self.conversation_ids, + } + + class ObservationCreateRequest(object): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = payload.get("occurredAt") + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + + def to_dict(self): + return { + "content": self.content, + "occurredAt": self.occurred_at, + "source": self.source, + "conversationIds": self.conversation_ids, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ObservationList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations".format( + **self._solution + ) + + def _create( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_observations_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ObservationInstance: + """ + Create the ObservationInstance + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ObservationInstance + """ + payload, _, _ = self._create( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ObservationInstance and return response metadata + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_observations_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ObservationInstance: + """ + Asynchronously create the ObservationInstance + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created ObservationInstance + """ + payload, _, _ = await self._create_async( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + create_observations_request: CreateObservationsRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ObservationInstance and return response metadata + + :param create_observations_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_observations_request=create_observations_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = ObservationInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ObservationInstance]: + """ + Streams ObservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ObservationInstance]: + """ + Asynchronously streams ObservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ObservationInstance]: + """ + Lists ObservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ObservationInstance]: + """ + Asynchronously lists ObservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ObservationInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param datetime created_after: Filter observations created after this timestamp (inclusive). + :param datetime created_before: Filter observations created before this timestamp (exclusive). + :param str conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + source=source, + created_after=created_after, + created_before=created_before, + conversation_id=conversation_id, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ObservationPage: + """ + Retrieve a single page of ObservationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ObservationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ObservationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> ObservationPage: + """ + Asynchronously retrieve a single page of ObservationInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of ObservationInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ObservationPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ObservationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ObservationPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + source: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param source: Filter by source. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :param created_after: Filter observations created after this timestamp (inclusive). + :param created_before: Filter observations created before this timestamp (exclusive). + :param conversation_id: Filter by conversation ID. Returns only items associated with the specified conversation. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ObservationPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "source": source, + "createdAfter": serialize.iso8601_datetime(created_after), + "createdBefore": serialize.iso8601_datetime(created_before), + "conversationId": conversation_id, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ObservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ObservationPage: + """ + Retrieve a specific page of ObservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ObservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ObservationPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ObservationPage: + """ + Asynchronously retrieve a specific page of ObservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ObservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ObservationPage(self._version, response, solution=self._solution) + + def get(self, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :param observation_id: The observation ID. + """ + return ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=observation_id, + ) + + def __call__(self, observation_id: str) -> ObservationContext: + """ + Constructs a ObservationContext + + :param observation_id: The observation ID. + """ + return ObservationContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=observation_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ObservationList>" diff --git a/twilio/rest/memory/v1/operation.py b/twilio/rest/memory/v1/operation.py new file mode 100644 index 0000000000..7c0c5aa8e0 --- /dev/null +++ b/twilio/rest/memory/v1/operation.py @@ -0,0 +1,279 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperationInstance(InstanceResource): + """ + :ivar operation_id: The unique identifier for this operation. + :ivar status: The current status of the operation. + :ivar created_at: When the operation was created. + :ivar status_url: URI to check operation status. + :ivar completed_at: When the operation completed or failed. + :ivar result: + :ivar error: + :ivar result_url: URL to fetch the resulting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + operation_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["OperationInstance.str"] = payload.get("status") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.status_url: Optional[str] = payload.get("statusUrl") + self.completed_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("completedAt") + ) + self.result: Optional[str] = payload.get("result") + self.error: Optional[str] = payload.get("error") + self.result_url: Optional[str] = payload.get("resultUrl") + + # Only set _solution if path params are provided (not None) + if operation_id is not None: + self._solution = { + "operation_id": operation_id, + } + + self._context: Optional[OperationContext] = None + + @property + def _proxy(self) -> "OperationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperationContext for this OperationInstance + """ + if self._context is None: + self._context = OperationContext( + self._version, + operation_id=self._solution["operation_id"], + ) + return self._context + + def fetch(self) -> "OperationInstance": + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperationInstance": + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.OperationInstance {}>".format(context) + + +class OperationContext(InstanceContext): + + def __init__(self, version: Version, operation_id: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param operation_id: The operation ID returned from a write endpoint. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "operation_id": operation_id, + } + self._uri = "/ControlPlane/Operations/{operation_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OperationInstance( + self._version, + payload, + operation_id=self._solution["operation_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.OperationContext {}>".format(context) + + +class OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __call__(self, operation_id: str) -> OperationContext: + """ + Constructs a OperationContext + + :param operation_id: The operation ID returned from a write endpoint. + """ + return OperationContext(self._version, operation_id=operation_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.OperationList>" diff --git a/twilio/rest/memory/v1/profile.py b/twilio/rest/memory/v1/profile.py new file mode 100644 index 0000000000..de1016ce6b --- /dev/null +++ b/twilio/rest/memory/v1/profile.py @@ -0,0 +1,1172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class ProfileInstance(InstanceResource): + """ + :ivar profiles: + :ivar meta: + :ivar message: + :ivar id: The canonical profile ID. + :ivar created_at: The time the profile was created. + :ivar traits: Multiple trait groups. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: Optional[str] = None, + ): + super().__init__(version) + + self.profiles: Optional[List[str]] = payload.get("profiles") + self.meta: Optional[IdentityProfilesMeta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + + self._context: Optional[ProfileContext] = None + + @property + def _proxy(self) -> "ProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ProfileContext for this ProfileInstance + """ + if self._context is None: + self._context = ProfileContext( + self._version, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ProfileInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ProfileInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, trait_groups: Union[str, object] = values.unset + ) -> "ProfileInstance": + """ + Fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + return self._proxy.fetch( + trait_groups=trait_groups, + ) + + async def fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> "ProfileInstance": + """ + Asynchronous coroutine to fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + return await self._proxy.fetch_async( + trait_groups=trait_groups, + ) + + def fetch_with_http_info( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ProfileInstance with HTTP info + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + trait_groups=trait_groups, + ) + + async def fetch_with_http_info_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProfileInstance with HTTP info + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + trait_groups=trait_groups, + ) + + def patch(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + return self._proxy.patch( + profile_patch=profile_patch, + ) + + async def patch_async(self, profile_patch: ProfilePatch) -> "ProfileInstance": + """ + Asynchronous coroutine to patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + return await self._proxy.patch_async( + profile_patch=profile_patch, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ProfileInstance {}>".format(context) + + +class ProfileContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the ProfileContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ProfileInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ProfileInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ProfileInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self, trait_groups: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "traitGroups": trait_groups, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch(self, trait_groups: Union[str, object] = values.unset) -> ProfileInstance: + """ + Fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + payload, _, _ = self._fetch(trait_groups=trait_groups) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def fetch_with_http_info( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ProfileInstance and return response metadata + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(trait_groups=trait_groups) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "traitGroups": trait_groups, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ProfileInstance: + """ + Asynchronous coroutine to fetch the ProfileInstance + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: The fetched ProfileInstance + """ + payload, _, _ = await self._fetch_async(trait_groups=trait_groups) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def fetch_with_http_info_async( + self, trait_groups: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProfileInstance and return response metadata + + :param trait_groups: Comma separated list of trait group names to include. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + trait_groups=trait_groups + ) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + payload, _, _ = self._patch(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def patch_with_http_info(self, profile_patch: ProfilePatch) -> ApiResponse: + """ + Patch the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(profile_patch=profile_patch) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async(self, profile_patch: ProfilePatch) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_patch.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async(self, profile_patch: ProfilePatch) -> ProfileInstance: + """ + Asynchronous coroutine to patch the ProfileInstance + + :param profile_patch: + + :returns: The patched ProfileInstance + """ + payload, _, _ = await self._patch_async(profile_patch=profile_patch) + return ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def patch_with_http_info_async( + self, profile_patch: ProfilePatch + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ProfileInstance and return response metadata + + :param profile_patch: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + profile_patch=profile_patch + ) + instance = ProfileInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.ProfileContext {}>".format(context) + + +class ProfilePage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ProfilePage>" + + +class ProfileList(ListResource): + + class IdentityProfilesMeta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + class ProfileData(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + class ProfilePatch(object): + """ + :ivar traits: Multiple trait groups. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.traits: Optional[Dict[str, Dict[str, object]]] = payload.get("traits") + + def to_dict(self): + return { + "traits": self.traits, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the ProfileList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/Stores/{store_id}/Profiles".format(**self._solution) + + def _create(self, profile_data: ProfileData) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_data.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, profile_data: ProfileData) -> ProfileInstance: + """ + Create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + payload, _, _ = self._create(profile_data=profile_data) + return ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info(self, profile_data: ProfileData) -> ApiResponse: + """ + Create the ProfileInstance and return response metadata + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(profile_data=profile_data) + instance = ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, profile_data: ProfileData) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_data.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, profile_data: ProfileData) -> ProfileInstance: + """ + Asynchronously create the ProfileInstance + + :param profile_data: + + :returns: The created ProfileInstance + """ + payload, _, _ = await self._create_async(profile_data=profile_data) + return ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, profile_data: ProfileData + ) -> ApiResponse: + """ + Asynchronously create the ProfileInstance and return response metadata + + :param profile_data: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + profile_data=profile_data + ) + instance = ProfileInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ProfileInstance]: + """ + Streams ProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ProfileInstance]: + """ + Asynchronously streams ProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Lists ProfileInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously lists ProfileInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ProfileInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ProfilePage: + """ + Retrieve a single page of ProfileInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ProfileInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ProfilePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ProfilePage: + """ + Asynchronously retrieve a single page of ProfileInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of ProfileInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ProfilePage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ProfilePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ProfilePage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ProfilePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ProfilePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ProfilePage: + """ + Retrieve a specific page of ProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ProfilePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ProfilePage: + """ + Asynchronously retrieve a specific page of ProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ProfilePage(self._version, response, solution=self._solution) + + def get(self, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + return ProfileContext( + self._version, store_id=self._solution["store_id"], profile_id=profile_id + ) + + def __call__(self, profile_id: str) -> ProfileContext: + """ + Constructs a ProfileContext + + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + """ + return ProfileContext( + self._version, store_id=self._solution["store_id"], profile_id=profile_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.ProfileList>" diff --git a/twilio/rest/memory/v1/recall.py b/twilio/rest/memory/v1/recall.py new file mode 100644 index 0000000000..ff759be74f --- /dev/null +++ b/twilio/rest/memory/v1/recall.py @@ -0,0 +1,382 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecallInstance(InstanceResource): + + class ParticipantType(object): + HUMAN_AGENT = "HUMAN_AGENT" + CUSTOMER = "CUSTOMER" + AI_AGENT = "AI_AGENT" + AGENT = "AGENT" + UNKNOWN = "UNKNOWN" + + """ + :ivar observations: Array of observation memories. + :ivar summaries: Array of summary memories derived from observations at the end of conversations. + :ivar communications: Array of recent communication context. + :ivar meta: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_id: str + ): + super().__init__(version) + + self.observations: Optional[List[str]] = payload.get("observations") + self.summaries: Optional[List[str]] = payload.get("summaries") + self.communications: Optional[List[str]] = payload.get("communications") + self.meta: Optional[str] = payload.get("meta") + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.RecallInstance {}>".format(context) + + +class RecallList(ListResource): + + class CommunicationContent(object): + """ + :ivar text: Primary text content (optional). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "text": self.text, + } + + class CommunicationRecipients(object): + """ + :ivar id: Participant identifier. + :ivar name: Participant display name + :ivar type: + :ivar profile_id: The canonical profile ID. + :ivar address: Address of the Participant (e.g., phone number, email address) + :ivar channel: The channel on which the message originated + :ivar delivery_status: Delivery status of the Communication to this recipient + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.type: Optional[ParticipantType] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + self.delivery_status: Optional[str] = payload.get("deliveryStatus") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "type": self.type.to_dict() if self.type is not None else None, + "profileId": self.profile_id, + "address": self.address, + "channel": self.channel, + "deliveryStatus": self.delivery_status, + } + + class MemoryRetrievalRequest(object): + """ + :ivar conversation_id: A unique identifier for the conversation using Twilio Type ID (TTID) format. + :ivar query: Hybrid search query for finding relevant memories. Omit to use query expansion to generate query from previous 10 communications in conversation. + :ivar begin_date: Start date for filtering memories (inclusive). + :ivar end_date: End date for filtering memories (exclusive). + :ivar communications_limit: Maximum number of conversational session memories to return. If omitted or set to 0, no session memories will be fetched. + :ivar observations_limit: Maximum number of observation memories to return. If omitted, defaults to 20. If set to 0, no observation memories will be fetched. + :ivar summaries_limit: Maximum number of summary memories to return. If omitted, defaults to 5. If set to 0, no summary memories will be fetched. + :ivar relevance_threshold: Minimum relevance score threshold for observations and summaries to be returned. Only memories with a relevance score greater than or equal to this threshold will be included in the response. This threshold only applies when results are ranked by relevance. When results are returned in most-recent order, this field has no effect. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.conversation_id: Optional[str] = payload.get("conversationId") + self.query: Optional[str] = payload.get("query") + self.begin_date: Optional[datetime] = payload.get("beginDate") + self.end_date: Optional[datetime] = payload.get("endDate") + self.communications_limit: Optional[int] = payload.get( + "communicationsLimit" + ) + self.observations_limit: Optional[int] = payload.get("observationsLimit") + self.summaries_limit: Optional[int] = payload.get("summariesLimit") + self.relevance_threshold: Optional[float] = payload.get( + "relevanceThreshold" + ) + + def to_dict(self): + return { + "conversationId": self.conversation_id, + "query": self.query, + "beginDate": self.begin_date, + "endDate": self.end_date, + "communicationsLimit": self.communications_limit, + "observationsLimit": self.observations_limit, + "summariesLimit": self.summaries_limit, + "relevanceThreshold": self.relevance_threshold, + } + + class Participant(object): + """ + :ivar id: Participant identifier. + :ivar name: Participant display name + :ivar type: + :ivar profile_id: The canonical profile ID. + :ivar address: Address of the Participant (e.g., phone number, email address) + :ivar channel: The channel on which the message originated + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.type: Optional[ParticipantType] = payload.get("type") + self.profile_id: Optional[str] = payload.get("profileId") + self.address: Optional[str] = payload.get("address") + self.channel: Optional[str] = payload.get("channel") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "type": self.type.to_dict() if self.type is not None else None, + "profileId": self.profile_id, + "address": self.address, + "channel": self.channel, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the RecallList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Recall".format( + **self._solution + ) + + def _create( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = memory_retrieval_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> RecallInstance: + """ + Create the RecallInstance + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created RecallInstance + """ + payload, _, _ = self._create( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecallInstance and return response metadata + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = memory_retrieval_request.to_dict() + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Encoding": content_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> RecallInstance: + """ + Asynchronously create the RecallInstance + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: The created RecallInstance + """ + payload, _, _ = await self._create_async( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + return RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, + memory_retrieval_request: MemoryRetrievalRequest, + accept_encoding: Union[str, object] = values.unset, + content_encoding: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RecallInstance and return response metadata + + :param memory_retrieval_request: + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param content_encoding: Compression algorithm used for the request body (e.g., gzip, deflate, br) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + memory_retrieval_request=memory_retrieval_request, + accept_encoding=accept_encoding, + content_encoding=content_encoding, + ) + instance = RecallInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.RecallList>" diff --git a/twilio/rest/memory/v1/revision.py b/twilio/rest/memory/v1/revision.py new file mode 100644 index 0000000000..34684c4081 --- /dev/null +++ b/twilio/rest/memory/v1/revision.py @@ -0,0 +1,592 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class RevisionInstance(InstanceResource): + """ + :ivar content: The main content of the observation. + :ivar occurred_at: The timestamp when the observation originally occurred. + :ivar source: The source system that generated this observation. Allows letters, numbers, spaces, and URL-safe symbols. Excludes URL-unsafe characters like quotes, angle brackets, and control characters. + :ivar conversation_ids: Array of conversation IDs associated with this observation. + :ivar id: A unique identifier for the observation using Twilio Type ID (TTID) format. + :ivar created_at: The timestamp when the observation was created. + :ivar updated_at: The timestamp when the observation was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + store_id: str, + profile_id: str, + observation_id: str, + ): + super().__init__(version) + + self.content: Optional[str] = payload.get("content") + self.occurred_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("occurredAt") + ) + self.source: Optional[str] = payload.get("source") + self.conversation_ids: Optional[List[str]] = payload.get("conversationIds") + self.id: Optional[str] = payload.get("id") + self.created_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("createdAt") + ) + self.updated_at: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updatedAt") + ) + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None or observation_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.RevisionInstance {}>".format(context) + + +class RevisionPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> RevisionInstance: + """ + Build an instance of RevisionInstance + + :param payload: Payload response from the API + """ + + return RevisionInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + observation_id=self._solution["observation_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.RevisionPage>" + + +class RevisionList(ListResource): + + def __init__( + self, version: Version, store_id: str, profile_id: str, observation_id: str + ): + """ + Initialize the RevisionList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + :param observation_id: The observation ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + "observation_id": observation_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Observations/{observation_id}/Revisions".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RevisionInstance]: + """ + Streams RevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RevisionInstance]: + """ + Asynchronously streams RevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RevisionInstance]: + """ + Lists RevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RevisionInstance]: + """ + Asynchronously lists RevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RevisionInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + accept_encoding=accept_encoding, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> RevisionPage: + """ + Retrieve a single page of RevisionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of RevisionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RevisionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + accept_encoding: Union[str, object] = values.unset, + ) -> RevisionPage: + """ + Asynchronously retrieve a single page of RevisionInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :returns: Page of RevisionInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RevisionPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RevisionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RevisionPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + accept_encoding: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param accept_encoding: Compression algorithms supported by the client (e.g., gzip, deflate, br) + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RevisionPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "Accept-Encoding": accept_encoding, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Accept-Encoding": accept_encoding, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> RevisionPage: + """ + Retrieve a specific page of RevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RevisionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RevisionPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RevisionPage: + """ + Asynchronously retrieve a specific page of RevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RevisionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RevisionPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.RevisionList>" diff --git a/twilio/rest/memory/v1/store.py b/twilio/rest/memory/v1/store.py new file mode 100644 index 0000000000..2821e49925 --- /dev/null +++ b/twilio/rest/memory/v1/store.py @@ -0,0 +1,1149 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class StoreInstance(InstanceResource): + """ + :ivar stores: List of Memory Store IDs associated with the Twilio account. + :ivar meta: + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + :ivar id: The unique identifier for the Memory Store + :ivar status: The current status of the Memory Store. A store begins in the QUEUED state as it is scheduled for processing. It then moves to PROVISIONING at the beginning of processing. It transitions to ACTIVE once all dependent resources are provisioned, including Conversational Intelligence capabilities. If there is an issue provisioning resources, the store will move to the FAILED state. + :ivar intelligence_service_id: The ID of the associated intelligence service that was provisioned for memory extraction. + :ivar version: The current version number of the Memory Store. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: Optional[str] = None, + ): + super().__init__(version) + + self.stores: Optional[List[str]] = payload.get("stores") + self.meta: Optional[Meta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.status: Optional["StoreInstance.str"] = payload.get("status") + self.intelligence_service_id: Optional[str] = payload.get( + "intelligenceServiceId" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None: + self._solution = { + "store_id": store_id, + } + + self._context: Optional[StoreContext] = None + + @property + def _proxy(self) -> "StoreContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StoreContext for this StoreInstance + """ + if self._context is None: + self._context = StoreContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the StoreInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the StoreInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "StoreInstance": + """ + Fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StoreInstance": + """ + Asynchronous coroutine to fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StoreInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StoreInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> "StoreInstance": + """ + Patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + return self._proxy.patch( + if_match=if_match, + patch_store_request=patch_store_request, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> "StoreInstance": + """ + Asynchronous coroutine to patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + patch_store_request=patch_store_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.StoreInstance {}>".format(context) + + +class StoreContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the StoreContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the StoreInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the StoreInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the StoreInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> StoreInstance: + """ + Fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + payload, _, _ = self._fetch() + return StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StoreInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> StoreInstance: + """ + Asynchronous coroutine to fetch the StoreInstance + + + :returns: The fetched StoreInstance + """ + payload, _, _ = await self._fetch_async() + return StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StoreInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = StoreInstance( + self._version, + payload, + store_id=self._solution["store_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_store_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> StoreInstance: + """ + Patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + payload, _, _ = self._patch( + if_match=if_match, patch_store_request=patch_store_request + ) + return StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> ApiResponse: + """ + Patch the StoreInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, patch_store_request=patch_store_request + ) + instance = StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_store_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> StoreInstance: + """ + Asynchronous coroutine to patch the StoreInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: The patched StoreInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, patch_store_request=patch_store_request + ) + return StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + patch_store_request: Union[PatchStoreRequest, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the StoreInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_store_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, patch_store_request=patch_store_request + ) + instance = StoreInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.StoreContext {}>".format(context) + + +class StorePage(TokenPagination): + + def get_instance(self, payload: str) -> str: + """ + Build an instance of str + + :param payload: Payload response from the API + """ + + return payload # Return string ID directly + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.StorePage>" + + +class StoreList(ListResource): + + class Meta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: The number of items returned in this page of results. + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + class PatchStoreRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + class ServiceRequest(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Store. This name is assigned by the developer and can be used in addition to the ID. It is intended to be human-readable and unique within the account. + :ivar description: A human readable description of this resource, up to 128 characters. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + } + + def __init__(self, version: Version): + """ + Initialize the StoreList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ControlPlane/Stores" + + def _create(self, service_request: ServiceRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = service_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, service_request: ServiceRequest) -> StoreInstance: + """ + Create the StoreInstance + + :param service_request: + + :returns: The created StoreInstance + """ + payload, _, _ = self._create(service_request=service_request) + return StoreInstance(self._version, payload) + + def create_with_http_info(self, service_request: ServiceRequest) -> ApiResponse: + """ + Create the StoreInstance and return response metadata + + :param service_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(service_request=service_request) + instance = StoreInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, service_request: ServiceRequest) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = service_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self, service_request: ServiceRequest) -> StoreInstance: + """ + Asynchronously create the StoreInstance + + :param service_request: + + :returns: The created StoreInstance + """ + payload, _, _ = await self._create_async(service_request=service_request) + return StoreInstance(self._version, payload) + + async def create_with_http_info_async( + self, service_request: ServiceRequest + ) -> ApiResponse: + """ + Asynchronously create the StoreInstance and return response metadata + + :param service_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + service_request=service_request + ) + instance = StoreInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StoreInstance]: + """ + Streams StoreInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[StoreInstance]: + """ + Asynchronously streams StoreInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, order_by=order_by, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Lists StoreInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously lists StoreInstance IDs from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists StoreInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> StorePage: + """ + Retrieve a single page of StoreInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of StoreInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StorePage(self._version, response, uri=self._uri, params=data) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> StorePage: + """ + Asynchronously retrieve a single page of StoreInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of StoreInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StorePage(self._version, response, uri=self._uri, params=data) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StorePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = StorePage(self._version, response, uri=self._uri) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StorePage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = StorePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> StorePage: + """ + Retrieve a specific page of StoreInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StoreInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return StorePage(self._version, response) + + async def get_page_async(self, target_url: str) -> StorePage: + """ + Asynchronously retrieve a specific page of StoreInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StoreInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return StorePage(self._version, response) + + def get(self, store_id: str) -> StoreContext: + """ + Constructs a StoreContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return StoreContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> StoreContext: + """ + Constructs a StoreContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return StoreContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.StoreList>" diff --git a/twilio/rest/memory/v1/trait.py b/twilio/rest/memory/v1/trait.py new file mode 100644 index 0000000000..dc317640a1 --- /dev/null +++ b/twilio/rest/memory/v1/trait.py @@ -0,0 +1,587 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class TraitInstance(InstanceResource): + """ + :ivar name: The name of the trait. + :ivar value: The value of a trait. Can be a string, integer, boolean, or an array of these types (arrays cannot contain nested arrays). + :ivar trait_group: The trait group name to which this trait belongs. + :ivar timestamp: The time the trait was created or last updated. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_id: str + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.value: Optional[Dict[str, object]] = payload.get("value") + self.trait_group: Optional[str] = payload.get("traitGroup") + self.timestamp: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("timestamp") + ) + + # Only set _solution if path params are provided (not None) + if store_id is not None or profile_id is not None: + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.TraitInstance {}>".format(context) + + +class TraitPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> TraitInstance: + """ + Build an instance of TraitInstance + + :param payload: Payload response from the API + """ + + return TraitInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.TraitPage>" + + +class TraitList(ListResource): + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the TraitList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param profile_id: The unique identifier for the profile using Twilio Type ID (TTID) format. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Traits".format( + **self._solution + ) + + def stream( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TraitInstance]: + """ + Streams TraitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TraitInstance]: + """ + Asynchronously streams TraitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitInstance]: + """ + Lists TraitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitInstance]: + """ + Asynchronously lists TraitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TraitInstance and returns headers from first page + + + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param str trait_groups: Comma separated list of trait group names to include. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + page_token=page_token, + order_by=order_by, + trait_groups=trait_groups, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + ) -> TraitPage: + """ + Retrieve a single page of TraitInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :returns: Page of TraitInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + ) -> TraitPage: + """ + Asynchronously retrieve a single page of TraitInstance records from the API. + Request is executed immediately + + :param page_size: The maximum number of items to return per page, maximum of 1000. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :returns: Page of TraitInstance + """ + data = values.of( + { + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TraitPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order_by: Union[str, object] = values.unset, + trait_groups: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param trait_groups: Comma separated list of trait group names to include. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitPage, status code, and headers + """ + data = values.of( + { + "pageToken": page_token, + "orderBy": order_by, + "traitGroups": trait_groups, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TraitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TraitPage: + """ + Retrieve a specific page of TraitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TraitPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TraitPage: + """ + Asynchronously retrieve a specific page of TraitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TraitPage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.TraitList>" diff --git a/twilio/rest/memory/v1/trait_group.py b/twilio/rest/memory/v1/trait_group.py new file mode 100644 index 0000000000..1412ffc70a --- /dev/null +++ b/twilio/rest/memory/v1/trait_group.py @@ -0,0 +1,1571 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, and conversational intelligence capabilities. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.token_pagination import TokenPagination + + +class TraitGroupInstance(InstanceResource): + """ + :ivar trait_group: + :ivar meta: + :ivar message: + :ivar status_url: URI to check operation status. + :ivar display_name: Provides a unique and addressable name to be assigned to this Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait's definition. + :ivar version: The current version number of the Trait Group. Incremented on each successful update. + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + trait_group_name: Optional[str] = None, + ): + super().__init__(version) + + self.trait_group: Optional[TraitGroup] = payload.get("traitGroup") + self.meta: Optional[Meta] = payload.get("meta") + self.message: Optional[str] = payload.get("message") + self.status_url: Optional[str] = payload.get("statusUrl") + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraits]] = payload.get("traits") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + # Only set _solution if path params are provided (not None) + if store_id is not None or trait_group_name is not None: + self._solution = { + "store_id": store_id, + "trait_group_name": trait_group_name, + } + + self._context: Optional[TraitGroupContext] = None + + @property + def _proxy(self) -> "TraitGroupContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TraitGroupContext for this TraitGroupInstance + """ + if self._context is None: + self._context = TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TraitGroupInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + return self._proxy.fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + async def fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Asynchronous coroutine to fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + return await self._proxy.fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + def fetch_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TraitGroupInstance with HTTP info + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + async def fetch_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TraitGroupInstance with HTTP info + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + return self._proxy.patch( + if_match=if_match, + patch_trait_group_request=patch_trait_group_request, + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> "TraitGroupInstance": + """ + Asynchronous coroutine to patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + return await self._proxy.patch_async( + if_match=if_match, + patch_trait_group_request=patch_trait_group_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.TraitGroupInstance {}>".format(context) + + +class TraitGroupContext(InstanceContext): + + def __init__(self, version: Version, store_id: str, trait_group_name: str): + """ + Initialize the TraitGroupContext + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + :param trait_group_name: A unique Name of the TraitGroup + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "trait_group_name": trait_group_name, + } + self._uri = ( + "/ControlPlane/Stores/{store_id}/TraitGroups/{trait_group_name}".format( + **self._solution + ) + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TraitGroupInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TraitGroupInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TraitGroupInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupInstance: + """ + Fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + payload, _, _ = self._fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + def fetch_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TraitGroupInstance and return response metadata + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupInstance: + """ + Asynchronous coroutine to fetch the TraitGroupInstance + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: The fetched TraitGroupInstance + """ + payload, _, _ = await self._fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + async def fetch_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TraitGroupInstance and return response metadata + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + include_traits=include_traits, + page_size=page_size, + page_token=page_token, + order_by=order_by, + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_trait_group_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + def patch( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> TraitGroupInstance: + """ + Patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + payload, _, _ = self._patch( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + def patch_with_http_info( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> ApiResponse: + """ + Patch the TraitGroupInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = patch_trait_group_request.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers + ) + + async def patch_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> TraitGroupInstance: + """ + Asynchronous coroutine to patch the TraitGroupInstance + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: The patched TraitGroupInstance + """ + payload, _, _ = await self._patch_async( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + return TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + + async def patch_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + patch_trait_group_request: Union[PatchTraitGroupRequest, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the TraitGroupInstance and return response metadata + + :param if_match: Allows for optimistic concurrency control by making the request conditional. Server will only act if the resource's current Entity Tag (ETag) matches the one provided, preventing accidental overwrites. + :param patch_trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + if_match=if_match, patch_trait_group_request=patch_trait_group_request + ) + instance = TraitGroupInstance( + self._version, + payload, + store_id=self._solution["store_id"], + trait_group_name=self._solution["trait_group_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Memory.V1.TraitGroupContext {}>".format(context) + + +class TraitGroupPage(TokenPagination): + + def get_instance(self, payload: Dict[str, Any]) -> TraitGroupInstance: + """ + Build an instance of TraitGroupInstance + + :param payload: Payload response from the API + """ + + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.TraitGroupPage>" + + +class TraitGroupList(ListResource): + + class Meta(object): + """ + :ivar key: The key of the list property contains the actual data items. This enables programmatic iteration over paginated results. + :ivar page_size: The number of items returned in this page of results. + :ivar next_token: + :ivar previous_token: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.key: Optional[str] = payload.get("key") + self.page_size: Optional[int] = payload.get("pageSize") + self.next_token: Optional[str] = payload.get("nextToken") + self.previous_token: Optional[str] = payload.get("previousToken") + + def to_dict(self): + return { + "key": self.key, + "pageSize": self.page_size, + "nextToken": self.next_token, + "previousToken": self.previous_token, + } + + class PatchTraitGroupRequest(object): + """ + :ivar description: Updated description of the Trait Group + :ivar traits: Map of traits to add, update, or remove in this Trait Group, where the key is the trait name. - To update/add a trait: provide the complete TraitDefinition object - To remove a trait: set dataType to an empty string (\"\") + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitDefinition]] = payload.get("traits") + + def to_dict(self): + return { + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + } + + class TraitDefinition(object): + """ + :ivar data_type: Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + :ivar description: Description of the Trait, providing additional context or information. + :ivar validation_rule: + :ivar id_type_promotion: The name of the identifier type to promote the trait value to, such as ''email'', ''phone'', ''user_id'', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.data_type: Optional[str] = payload.get("dataType") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get( + "validationRule" + ) + self.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "validationRule": ( + self.validation_rule.to_dict() + if self.validation_rule is not None + else None + ), + "idTypePromotion": self.id_type_promotion, + } + + class TraitGroup(object): + """ + :ivar display_name: Provides a unique and addressable name to be assigned to this Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits that are part of this Trait Group, where the key is the trait name and the value is the trait's definition. + :ivar version: The current version number of the Trait Group. Incremented on each successful update. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupCoreTraits]] = payload.get( + "traits" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + "version": self.version, + } + + class TraitGroupCoreTraits(object): + """ + :ivar data_type: Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + :ivar description: Description of the Trait, providing additional context or information. + :ivar validation_rule: + :ivar id_type_promotion: The name of the identifier type to promote the trait value to, such as ''email'', ''phone'', ''user_id'', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.data_type: Optional[str] = payload.get("dataType") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get( + "validationRule" + ) + self.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "validationRule": ( + self.validation_rule.to_dict() + if self.validation_rule is not None + else None + ), + "idTypePromotion": self.id_type_promotion, + } + + class TraitGroupRequest(object): + """ + :ivar display_name: Unique name of the Trait Group + :ivar description: description of the Trait Group + :ivar traits: Map of traits belonging to this Trait Group, keyed by trait name. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.display_name: Optional[str] = payload.get("displayName") + self.description: Optional[str] = payload.get("description") + self.traits: Optional[Dict[str, TraitGroupRequestTraits]] = payload.get( + "traits" + ) + + def to_dict(self): + return { + "displayName": self.display_name, + "description": self.description, + "traits": ( + {k: v.to_dict() for k, v in self.traits.items()} + if self.traits is not None + else None + ), + } + + class TraitGroupRequestTraits(object): + """ + :ivar data_type: Data type of the Trait, such as STRING, NUMBER, BOOLEAN, ARRAY. For DELETE operations in PATCH requests, set this to an empty string (\"\") to mark the trait for deletion. + :ivar description: Description of the Trait, providing additional context or information. + :ivar validation_rule: + :ivar id_type_promotion: The name of the identifier type to promote the trait value to, such as ''email'', ''phone'', ''user_id'', etc. This allows the trait to be mapped to an identifier in Identity Resolution. The identifier type should be configured in the Identity Resolution Settings. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.data_type: Optional[str] = payload.get("dataType") + self.description: Optional[str] = payload.get("description") + self.validation_rule: Optional[ValidationRule] = payload.get( + "validationRule" + ) + self.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "validationRule": ( + self.validation_rule.to_dict() + if self.validation_rule is not None + else None + ), + "idTypePromotion": self.id_type_promotion, + } + + class ValidationRule(object): + """ + :ivar pattern: Regex pattern (max 1000 chars) + :ivar min_length: Minimum string length + :ivar max_length: Maximum string length + :ivar rule_type: Discriminator field indicating this is an array validation rule. + :ivar min: Minimum value + :ivar max: Maximum value + :ivar min_items: Minimum number of items + :ivar max_items: Maximum number of items + """ + + def __init__(self, payload: Dict[str, Any]): + + self.pattern: Optional[str] = payload.get("pattern") + self.min_length: Optional[int] = payload.get("minLength") + self.max_length: Optional[int] = payload.get("maxLength") + self.rule_type: Optional[str] = payload.get("ruleType") + self.min: Optional[float] = payload.get("min") + self.max: Optional[float] = payload.get("max") + self.min_items: Optional[int] = payload.get("minItems") + self.max_items: Optional[int] = payload.get("maxItems") + + def to_dict(self): + return { + "pattern": self.pattern, + "minLength": self.min_length, + "maxLength": self.max_length, + "ruleType": self.rule_type, + "min": self.min, + "max": self.max, + "minItems": self.min_items, + "maxItems": self.max_items, + } + + def __init__(self, version: Version, store_id: str): + """ + Initialize the TraitGroupList + + :param version: Version that contains the resource + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + } + self._uri = "/ControlPlane/Stores/{store_id}/TraitGroups".format( + **self._solution + ) + + def _create( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trait_group_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> TraitGroupInstance: + """ + Create the TraitGroupInstance + + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = self._create(trait_group_request=trait_group_request) + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + def create_with_http_info( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the TraitGroupInstance and return response metadata + + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + trait_group_request=trait_group_request + ) + instance = TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trait_group_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> TraitGroupInstance: + """ + Asynchronously create the TraitGroupInstance + + :param trait_group_request: + + :returns: The created TraitGroupInstance + """ + payload, _, _ = await self._create_async( + trait_group_request=trait_group_request + ) + return TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + + async def create_with_http_info_async( + self, trait_group_request: Union[TraitGroupRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TraitGroupInstance and return response metadata + + :param trait_group_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + trait_group_request=trait_group_request + ) + instance = TraitGroupInstance( + self._version, payload, store_id=self._solution["store_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TraitGroupInstance]: + """ + Streams TraitGroupInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TraitGroupInstance]: + """ + Asynchronously streams TraitGroupInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitGroupInstance]: + """ + Lists TraitGroupInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TraitGroupInstance]: + """ + Asynchronously lists TraitGroupInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TraitGroupInstance and returns headers from first page + + + :param bool include_traits: Whether to include trait definitions in the response + :param str page_token: The token for the page of results to retrieve. + :param str order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + include_traits=include_traits, + page_token=page_token, + order_by=order_by, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupPage: + """ + Retrieve a single page of TraitGroupInstance records from the API. + Request is executed immediately + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of TraitGroupInstance + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitGroupPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + include_traits: Union[bool, object] = values.unset, + page_size: Union[int, object] = values.unset, + page_token: Union[str, object] = values.unset, + order_by: Union[str, object] = values.unset, + ) -> TraitGroupPage: + """ + Asynchronously retrieve a single page of TraitGroupInstance records from the API. + Request is executed immediately + + :param include_traits: Whether to include trait definitions in the response + :param page_size: The maximum number of items to return per page, maximum of 100. + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :returns: Page of TraitGroupInstance + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageSize": page_size, + "pageToken": page_token, + "orderBy": order_by, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TraitGroupPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + def page_with_http_info( + self, + include_traits: Union[bool, object] = values.unset, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param include_traits: Whether to include trait definitions in the response + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitGroupPage, status code, and headers + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TraitGroupPage( + self._version, response, uri=self._uri, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + include_traits: Union[bool, object] = values.unset, + order_by: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param include_traits: Whether to include trait definitions in the response + :param page_token: The token for the page of results to retrieve. + :param order_by: Either 'ASC' or 'DESC' to sort results ascending or descending respectively. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TraitGroupPage, status code, and headers + """ + data = values.of( + { + "includeTraits": serialize.boolean_to_string(include_traits), + "pageToken": page_token, + "orderBy": order_by, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TraitGroupPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TraitGroupPage: + """ + Retrieve a specific page of TraitGroupInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitGroupInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TraitGroupPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TraitGroupPage: + """ + Asynchronously retrieve a specific page of TraitGroupInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TraitGroupInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TraitGroupPage(self._version, response, solution=self._solution) + + def get(self, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=trait_group_name, + ) + + def __call__(self, trait_group_name: str) -> TraitGroupContext: + """ + Constructs a TraitGroupContext + + :param trait_group_name: A unique Name of the TraitGroup + """ + return TraitGroupContext( + self._version, + store_id=self._solution["store_id"], + trait_group_name=trait_group_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Memory.V1.TraitGroupList>" diff --git a/twilio/rest/messaging/MessagingBase.py b/twilio/rest/messaging/MessagingBase.py index 4fff74d914..18b7f3e1a6 100644 --- a/twilio/rest/messaging/MessagingBase.py +++ b/twilio/rest/messaging/MessagingBase.py @@ -14,6 +14,8 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.messaging.v1 import V1 +from twilio.rest.messaging.v2 import V2 +from twilio.rest.messaging.v3 import V3 class MessagingBase(Domain): @@ -26,6 +28,8 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://messaging.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -36,6 +40,24 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Messaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Messaging + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/__init__.py b/twilio/rest/messaging/v1/__init__.py index 6bd630fbd8..1e1100e32e 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -22,6 +22,7 @@ from twilio.rest.messaging.v1.domain_config_messaging_service import ( DomainConfigMessagingServiceList, ) +from twilio.rest.messaging.v1.domain_validate_dn import DomainValidateDnList from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList from twilio.rest.messaging.v1.linkshortening_messaging_service import ( LinkshorteningMessagingServiceList, @@ -51,6 +52,7 @@ def __init__(self, domain: Domain): self._domain_config_messaging_service: Optional[ DomainConfigMessagingServiceList ] = None + self._domain_validate_dns: Optional[DomainValidateDnList] = None self._external_campaign: Optional[ExternalCampaignList] = None self._linkshortening_messaging_service: Optional[ LinkshorteningMessagingServiceList @@ -95,6 +97,12 @@ def domain_config_messaging_service(self) -> DomainConfigMessagingServiceList: ) return self._domain_config_messaging_service + @property + def domain_validate_dns(self) -> DomainValidateDnList: + if self._domain_validate_dns is None: + self._domain_validate_dns = DomainValidateDnList(self) + return self._domain_validate_dns + @property def external_campaign(self) -> ExternalCampaignList: if self._external_campaign is None: diff --git a/twilio/rest/messaging/v1/brand_registration/__init__.py b/twilio/rest/messaging/v1/brand_registration/__init__.py index e8c2ac40d5..349d7ba4f3 100644 --- a/twilio/rest/messaging/v1/brand_registration/__init__.py +++ b/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,7 +47,9 @@ class Status(object): APPROVED = "APPROVED" FAILED = "FAILED" IN_REVIEW = "IN_REVIEW" - DELETED = "DELETED" + DELETION_PENDING = "DELETION_PENDING" + DELETION_FAILED = "DELETION_FAILED" + SUSPENDED = "SUSPENDED" """ :ivar sid: The unique string to identify Brand Registration. @@ -120,6 +123,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[BrandRegistrationContext] = None @property @@ -155,6 +159,24 @@ async def fetch_async(self) -> "BrandRegistrationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self) -> "BrandRegistrationInstance": """ Update the BrandRegistrationInstance @@ -173,6 +195,24 @@ async def update_async(self) -> "BrandRegistrationInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async() + @property def brand_registration_otps(self) -> BrandRegistrationOtpList: """ @@ -217,54 +257,102 @@ def __init__(self, version: Version, sid: str): self._brand_registration_otps: Optional[BrandRegistrationOtpList] = None self._brand_vettings: Optional[BrandVettingList] = None - def fetch(self) -> BrandRegistrationInstance: + def _fetch(self) -> tuple: """ - Fetch the BrandRegistrationInstance - + Internal helper for fetch operation - :returns: The fetched BrandRegistrationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> BrandRegistrationInstance: + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + payload, _, _ = self._fetch() return BrandRegistrationInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> BrandRegistrationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BrandRegistrationInstance + Fetch the BrandRegistrationInstance and return response metadata - :returns: The fetched BrandRegistrationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + payload, _, _ = await self._fetch_async() return BrandRegistrationInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self) -> BrandRegistrationInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the BrandRegistrationInstance + Asynchronous coroutine to fetch the BrandRegistrationInstance and return response metadata - :returns: The updated BrandRegistrationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -272,20 +360,41 @@ def update(self) -> BrandRegistrationInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self) -> BrandRegistrationInstance: + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + payload, _, _ = self._update() return BrandRegistrationInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async(self) -> BrandRegistrationInstance: + def update_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to update the BrandRegistrationInstance + Update the BrandRegistrationInstance and return response metadata - :returns: The updated BrandRegistrationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -293,14 +402,35 @@ async def update_async(self) -> BrandRegistrationInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + payload, _, _ = await self._update_async() return BrandRegistrationInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the BrandRegistrationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def brand_registration_otps(self) -> BrandRegistrationOtpList: """ @@ -343,6 +473,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BrandRegistrationInstance: :param payload: Payload response from the API """ + return BrandRegistrationInstance(self._version, payload) def __repr__(self) -> str: @@ -367,24 +498,19 @@ def __init__(self, version: Version): self._uri = "/a2p/BrandRegistrations" - def create( + def _create( self, customer_profile_bundle_sid: str, a2p_profile_bundle_sid: str, brand_type: Union[str, object] = values.unset, mock: Union[bool, object] = values.unset, skip_automatic_sec_vet: Union[bool, object] = values.unset, - ) -> BrandRegistrationInstance: + ) -> tuple: """ - Create the BrandRegistrationInstance - - :param customer_profile_bundle_sid: Customer Profile Bundle Sid. - :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. - :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. - :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. - :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + Internal helper for create operation - :returns: The created BrandRegistrationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -404,13 +530,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return BrandRegistrationInstance(self._version, payload) - - async def create_async( + def create( self, customer_profile_bundle_sid: str, a2p_profile_bundle_sid: str, @@ -419,7 +543,7 @@ async def create_async( skip_automatic_sec_vet: Union[bool, object] = values.unset, ) -> BrandRegistrationInstance: """ - Asynchronously create the BrandRegistrationInstance + Create the BrandRegistrationInstance :param customer_profile_bundle_sid: Customer Profile Bundle Sid. :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. @@ -429,6 +553,58 @@ async def create_async( :returns: The created BrandRegistrationInstance """ + payload, _, _ = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + return BrandRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the BrandRegistrationInstance and return response metadata + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -447,12 +623,67 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Asynchronously create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + payload, _, _ = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) return BrandRegistrationInstance(self._version, payload) + async def create_with_http_info_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationInstance and return response metadata + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -503,6 +734,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -522,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -548,6 +830,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -556,6 +839,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BrandRegistrationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -622,6 +955,76 @@ async def page_async( ) return BrandRegistrationPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandRegistrationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BrandRegistrationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandRegistrationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BrandRegistrationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> BrandRegistrationPage: """ Retrieve a specific page of BrandRegistrationInstance records from the API. diff --git a/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py index 415dec9589..0ac2f302c5 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,48 +71,96 @@ def __init__(self, version: Version, brand_registration_sid: str): **self._solution ) - def create(self) -> BrandRegistrationOtpInstance: + def _create(self) -> tuple: """ - Create the BrandRegistrationOtpInstance - + Internal helper for create operation - :returns: The created BrandRegistrationOtpInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.create(method="POST", uri=self._uri, headers=headers) + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> BrandRegistrationOtpInstance: + """ + Create the BrandRegistrationOtpInstance + + :returns: The created BrandRegistrationOtpInstance + """ + payload, _, _ = self._create() return BrandRegistrationOtpInstance( self._version, payload, brand_registration_sid=self._solution["brand_registration_sid"], ) - async def create_async(self) -> BrandRegistrationOtpInstance: + def create_with_http_info(self) -> ApiResponse: """ - Asynchronously create the BrandRegistrationOtpInstance + Create the BrandRegistrationOtpInstance and return response metadata - :returns: The created BrandRegistrationOtpInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, headers=headers ) + async def create_async(self) -> BrandRegistrationOtpInstance: + """ + Asynchronously create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + payload, _, _ = await self._create_async() return BrandRegistrationOtpInstance( self._version, payload, brand_registration_sid=self._solution["brand_registration_sid"], ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationOtpInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py index 680be65037..9cd9243470 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -26,6 +27,7 @@ class BrandVettingInstance(InstanceResource): class VettingProvider(object): CAMPAIGN_VERIFY = "campaign-verify" + AEGIS = "aegis" """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the vetting record. @@ -70,6 +72,7 @@ def __init__( "brand_sid": brand_sid, "brand_vetting_sid": brand_vetting_sid or self.brand_vetting_sid, } + self._context: Optional[BrandVettingContext] = None @property @@ -106,6 +109,24 @@ async def fetch_async(self) -> "BrandVettingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -139,20 +160,30 @@ def __init__(self, version: Version, brand_sid: str, brand_vetting_sid: str): ) ) - def fetch(self) -> BrandVettingInstance: + def _fetch(self) -> tuple: """ - Fetch the BrandVettingInstance + Internal helper for fetch operation - - :returns: The fetched BrandVettingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BrandVettingInstance: + """ + Fetch the BrandVettingInstance + + :returns: The fetched BrandVettingInstance + """ + payload, _, _ = self._fetch() return BrandVettingInstance( self._version, payload, @@ -160,22 +191,46 @@ def fetch(self) -> BrandVettingInstance: brand_vetting_sid=self._solution["brand_vetting_sid"], ) - async def fetch_async(self) -> BrandVettingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BrandVettingInstance + Fetch the BrandVettingInstance and return response metadata - :returns: The fetched BrandVettingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BrandVettingInstance: + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + payload, _, _ = await self._fetch_async() return BrandVettingInstance( self._version, payload, @@ -183,6 +238,22 @@ async def fetch_async(self) -> BrandVettingInstance: brand_vetting_sid=self._solution["brand_vetting_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandVettingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BrandVettingInstance: :param payload: Payload response from the API """ + return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) @@ -234,18 +306,16 @@ def __init__(self, version: Version, brand_sid: str): **self._solution ) - def create( + def _create( self, vetting_provider: "BrandVettingInstance.VettingProvider", vetting_id: Union[str, object] = values.unset, - ) -> BrandVettingInstance: + ) -> tuple: """ - Create the BrandVettingInstance - - :param vetting_provider: - :param vetting_id: The unique ID of the vetting + Internal helper for create operation - :returns: The created BrandVettingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -260,26 +330,61 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + payload, _, _ = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) - async def create_async( + def create_with_http_info( self, vetting_provider: "BrandVettingInstance.VettingProvider", vetting_id: Union[str, object] = values.unset, - ) -> BrandVettingInstance: + ) -> ApiResponse: """ - Asynchronously create the BrandVettingInstance + Create the BrandVettingInstance and return response metadata :param vetting_provider: :param vetting_id: The unique ID of the vetting - :returns: The created BrandVettingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -294,14 +399,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Asynchronously create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + payload, _, _ = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) + async def create_with_http_info_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BrandVettingInstance and return response metadata + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, vetting_provider: Union[ @@ -364,6 +506,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BrandVettingInstance and returns headers from first page + + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BrandVettingInstance and returns headers from first page + + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, vetting_provider: Union[ @@ -387,6 +589,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( vetting_provider=vetting_provider, @@ -418,6 +621,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -427,6 +631,66 @@ async def list_async( ) ] + def list_with_http_info( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BrandVettingInstance and returns headers from first page + + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BrandVettingInstance and returns headers from first page + + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, vetting_provider: Union[ @@ -463,7 +727,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BrandVettingPage(self._version, response, self._solution) + return BrandVettingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -501,7 +765,87 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BrandVettingPage(self._version, response, self._solution) + return BrandVettingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandVettingPage, status code, and headers + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BrandVettingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BrandVettingPage, status code, and headers + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BrandVettingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BrandVettingPage: """ @@ -513,7 +857,7 @@ def get_page(self, target_url: str) -> BrandVettingPage: :returns: Page of BrandVettingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BrandVettingPage(self._version, response, self._solution) + return BrandVettingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BrandVettingPage: """ @@ -525,7 +869,7 @@ async def get_page_async(self, target_url: str) -> BrandVettingPage: :returns: Page of BrandVettingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BrandVettingPage(self._version, response, self._solution) + return BrandVettingPage(self._version, response, solution=self._solution) def get(self, brand_vetting_sid: str) -> BrandVettingContext: """ diff --git a/twilio/rest/messaging/v1/deactivations.py b/twilio/rest/messaging/v1/deactivations.py index e2cbf17a94..ddcbff4af8 100644 --- a/twilio/rest/messaging/v1/deactivations.py +++ b/twilio/rest/messaging/v1/deactivations.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,34 @@ async def fetch_async( date=date, ) + def fetch_with_http_info( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Fetch the DeactivationsInstance with HTTP info + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + date=date, + ) + + async def fetch_with_http_info_async( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeactivationsInstance with HTTP info + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + date=date, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -97,16 +126,15 @@ def __init__(self, version: Version): self._uri = "/Deactivations" - def fetch(self, date: Union[date, object] = values.unset) -> DeactivationsInstance: + def _fetch(self, date: Union[date, object] = values.unset) -> tuple: """ - Fetch the DeactivationsInstance + Internal helper for fetch operation - :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. - - :returns: The fetched DeactivationsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Date": serialize.iso8601_date(date), } @@ -116,27 +144,50 @@ def fetch(self, date: Union[date, object] = values.unset) -> DeactivationsInstan headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch(self, date: Union[date, object] = values.unset) -> DeactivationsInstance: + """ + Fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + payload, _, _ = self._fetch(date=date) return DeactivationsInstance( self._version, payload, ) - async def fetch_async( + def fetch_with_http_info( self, date: Union[date, object] = values.unset - ) -> DeactivationsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the DeactivationsInstance + Fetch the DeactivationsInstance and return response metadata :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. - :returns: The fetched DeactivationsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(date=date) + instance = DeactivationsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, date: Union[date, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Date": serialize.iso8601_date(date), } @@ -146,15 +197,43 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, date: Union[date, object] = values.unset + ) -> DeactivationsInstance: + """ + Asynchronous coroutine to fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + payload, _, _ = await self._fetch_async(date=date) return DeactivationsInstance( self._version, payload, ) + async def fetch_with_http_info_async( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeactivationsInstance and return response metadata + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(date=date) + instance = DeactivationsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/domain_certs.py b/twilio/rest/messaging/v1/domain_certs.py index 6da256cdb0..76fea05f18 100644 --- a/twilio/rest/messaging/v1/domain_certs.py +++ b/twilio/rest/messaging/v1/domain_certs.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainCertsContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DomainCertsInstance": """ Fetch the DomainCertsInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "DomainCertsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, tls_cert: str) -> "DomainCertsInstance": """ Update the DomainCertsInstance @@ -138,6 +176,30 @@ async def update_async(self, tls_cert: str) -> "DomainCertsInstance": tls_cert=tls_cert, ) + def update_with_http_info(self, tls_cert: str) -> ApiResponse: + """ + Update the DomainCertsInstance with HTTP info + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + tls_cert=tls_cert, + ) + + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance with HTTP info + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + tls_cert=tls_cert, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -167,6 +229,20 @@ def __init__(self, version: Version, domain_sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DomainCertsInstance @@ -174,10 +250,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -186,62 +284,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> DomainCertsInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the DomainCertsInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched DomainCertsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = self._fetch() return DomainCertsInstance( self._version, payload, domain_sid=self._solution["domain_sid"], ) - async def fetch_async(self) -> DomainCertsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DomainCertsInstance + Fetch the DomainCertsInstance and return response metadata - :returns: The fetched DomainCertsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = await self._fetch_async() return DomainCertsInstance( self._version, payload, domain_sid=self._solution["domain_sid"], ) - def update(self, tls_cert: str) -> DomainCertsInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the DomainCertsInstance + Asynchronous coroutine to fetch the DomainCertsInstance and return response metadata - :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. - :returns: The updated DomainCertsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, tls_cert: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -255,21 +406,43 @@ def update(self, tls_cert: str) -> DomainCertsInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, tls_cert: str) -> DomainCertsInstance: + """ + Update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + payload, _, _ = self._update(tls_cert=tls_cert) return DomainCertsInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) - async def update_async(self, tls_cert: str) -> DomainCertsInstance: + def update_with_http_info(self, tls_cert: str) -> ApiResponse: """ - Asynchronous coroutine to update the DomainCertsInstance + Update the DomainCertsInstance and return response metadata :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. - :returns: The updated DomainCertsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(tls_cert=tls_cert) + instance = DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, tls_cert: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -283,14 +456,37 @@ async def update_async(self, tls_cert: str) -> DomainCertsInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, tls_cert: str) -> DomainCertsInstance: + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + payload, _, _ = await self._update_async(tls_cert=tls_cert) return DomainCertsInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance and return response metadata + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(tls_cert=tls_cert) + instance = DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/domain_config.py b/twilio/rest/messaging/v1/domain_config.py index ed70351077..1fa8341f21 100644 --- a/twilio/rest/messaging/v1/domain_config.py +++ b/twilio/rest/messaging/v1/domain_config.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -59,6 +60,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainConfigContext] = None @property @@ -94,6 +96,24 @@ async def fetch_async(self) -> "DomainConfigInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, fallback_url: Union[str, object] = values.unset, @@ -142,6 +162,54 @@ async def update_async( disable_https=disable_https, ) + def update_with_http_info( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the DomainConfigInstance with HTTP info + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + async def update_with_http_info_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainConfigInstance with HTTP info + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,64 +239,108 @@ def __init__(self, version: Version, domain_sid: str): **self._solution ) - def fetch(self) -> DomainConfigInstance: + def _fetch(self) -> tuple: """ - Fetch the DomainConfigInstance - + Internal helper for fetch operation - :returns: The fetched DomainConfigInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DomainConfigInstance: + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + payload, _, _ = self._fetch() return DomainConfigInstance( self._version, payload, domain_sid=self._solution["domain_sid"], ) - async def fetch_async(self) -> DomainConfigInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DomainConfigInstance + Fetch the DomainConfigInstance and return response metadata - :returns: The fetched DomainConfigInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DomainConfigInstance: + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + payload, _, _ = await self._fetch_async() return DomainConfigInstance( self._version, payload, domain_sid=self._solution["domain_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, continue_on_failure: Union[bool, object] = values.unset, disable_https: Union[bool, object] = values.unset, - ) -> DomainConfigInstance: + ) -> tuple: """ - Update the DomainConfigInstance + Internal helper for update operation - :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. - :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links - :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service - :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. - - :returns: The updated DomainConfigInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -245,30 +357,77 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + payload, _, _ = self._update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) return DomainConfigInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) - async def update_async( + def update_with_http_info( self, fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, continue_on_failure: Union[bool, object] = values.unset, disable_https: Union[bool, object] = values.unset, - ) -> DomainConfigInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the DomainConfigInstance + Update the DomainConfigInstance and return response metadata :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. - :returns: The updated DomainConfigInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + instance = DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -285,14 +444,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Asynchronous coroutine to update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + payload, _, _ = await self._update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) return DomainConfigInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) + async def update_with_http_info_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainConfigInstance and return response metadata + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + instance = DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/domain_config_messaging_service.py b/twilio/rest/messaging/v1/domain_config_messaging_service.py index 2bcd4aa88c..b8291f2585 100644 --- a/twilio/rest/messaging/v1/domain_config_messaging_service.py +++ b/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[DomainConfigMessagingServiceContext] = None @property @@ -95,6 +97,24 @@ async def fetch_async(self) -> "DomainConfigMessagingServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,48 +146,96 @@ def __init__(self, version: Version, messaging_service_sid: str): **self._solution ) - def fetch(self) -> DomainConfigMessagingServiceInstance: + def _fetch(self) -> tuple: """ - Fetch the DomainConfigMessagingServiceInstance + Internal helper for fetch operation - - :returns: The fetched DomainConfigMessagingServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> DomainConfigMessagingServiceInstance: + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + payload, _, _ = self._fetch() return DomainConfigMessagingServiceInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def fetch_async(self) -> DomainConfigMessagingServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + Fetch the DomainConfigMessagingServiceInstance and return response metadata - :returns: The fetched DomainConfigMessagingServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DomainConfigMessagingServiceInstance: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + payload, _, _ = await self._fetch_async() return DomainConfigMessagingServiceInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/domain_validate_dn.py b/twilio/rest/messaging/v1/domain_validate_dn.py new file mode 100644 index 0000000000..04bac787e0 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_validate_dn.py @@ -0,0 +1,264 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainValidateDnInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar is_valid: + :ivar reason: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.is_valid: Optional[bool] = payload.get("is_valid") + self.reason: Optional[str] = payload.get("reason") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + + self._context: Optional[DomainValidateDnContext] = None + + @property + def _proxy(self) -> "DomainValidateDnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainValidateDnContext for this DomainValidateDnInstance + """ + if self._context is None: + self._context = DomainValidateDnContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def fetch(self) -> "DomainValidateDnInstance": + """ + Fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainValidateDnInstance": + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainValidateDnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainValidateDnInstance {}>".format(context) + + +class DomainValidateDnContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainValidateDnContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/ValidateDns".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainValidateDnInstance: + """ + Fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + payload, _, _ = self._fetch() + return DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainValidateDnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainValidateDnInstance: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance + + + :returns: The fetched DomainValidateDnInstance + """ + payload, _, _ = await self._fetch_async() + return DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainValidateDnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainValidateDnInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainValidateDnContext {}>".format(context) + + +class DomainValidateDnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainValidateDnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainValidateDnContext: + """ + Constructs a DomainValidateDnContext + + :param domain_sid: Unique string used to identify the domain. + """ + return DomainValidateDnContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainValidateDnContext: + """ + Constructs a DomainValidateDnContext + + :param domain_sid: Unique string used to identify the domain. + """ + return DomainValidateDnContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DomainValidateDnList>" diff --git a/twilio/rest/messaging/v1/external_campaign.py b/twilio/rest/messaging/v1/external_campaign.py index eed039a6cc..dd16e80319 100644 --- a/twilio/rest/messaging/v1/external_campaign.py +++ b/twilio/rest/messaging/v1/external_campaign.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,20 +65,17 @@ def __init__(self, version: Version): self._uri = "/Services/PreregisteredUsa2p" - def create( + def _create( self, campaign_id: str, messaging_service_sid: str, cnp_migration: Union[bool, object] = values.unset, - ) -> ExternalCampaignInstance: + ) -> tuple: """ - Create the ExternalCampaignInstance + Internal helper for create operation - :param campaign_id: ID of the preregistered campaign. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. - :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. - - :returns: The created ExternalCampaignInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -93,20 +91,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ExternalCampaignInstance(self._version, payload) - - async def create_async( + def create( self, campaign_id: str, messaging_service_sid: str, cnp_migration: Union[bool, object] = values.unset, ) -> ExternalCampaignInstance: """ - Asynchronously create the ExternalCampaignInstance + Create the ExternalCampaignInstance :param campaign_id: ID of the preregistered campaign. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. @@ -114,6 +110,48 @@ async def create_async( :returns: The created ExternalCampaignInstance """ + payload, _, _ = self._create( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + return ExternalCampaignInstance(self._version, payload) + + def create_with_http_info( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ExternalCampaignInstance and return response metadata + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + instance = ExternalCampaignInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -128,12 +166,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Asynchronously create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + payload, _, _ = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) return ExternalCampaignInstance(self._version, payload) + async def create_with_http_info_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ExternalCampaignInstance and return response metadata + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + instance = ExternalCampaignInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service.py b/twilio/rest/messaging/v1/linkshortening_messaging_service.py index ac69842a0c..9549b84828 100644 --- a/twilio/rest/messaging/v1/linkshortening_messaging_service.py +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[LinkshorteningMessagingServiceContext] = None @property @@ -81,6 +83,24 @@ async def create_async(self) -> "LinkshorteningMessagingServiceInstance": """ return await self._proxy.create_async() + def create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + def delete(self) -> bool: """ Deletes the LinkshorteningMessagingServiceInstance @@ -99,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -132,6 +170,23 @@ def __init__(self, version: Version, domain_sid: str, messaging_service_sid: str **self._solution ) + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create(self) -> LinkshorteningMessagingServiceInstance: """ Create the LinkshorteningMessagingServiceInstance @@ -139,16 +194,46 @@ def create(self) -> LinkshorteningMessagingServiceInstance: :returns: The created LinkshorteningMessagingServiceInstance """ - data = values.of({}) + payload, _, _ = self._create() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) - payload = self._version.create(method="POST", uri=self._uri, data=data) + def create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance and return response metadata - return LinkshorteningMessagingServiceInstance( + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = LinkshorteningMessagingServiceInstance( self._version, payload, domain_sid=self._solution["domain_sid"], messaging_service_sid=self._solution["messaging_service_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async(self) -> LinkshorteningMessagingServiceInstance: """ @@ -157,18 +242,43 @@ async def create_async(self) -> LinkshorteningMessagingServiceInstance: :returns: The created LinkshorteningMessagingServiceInstance """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + payload, _, _ = await self._create_async() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], ) - return LinkshorteningMessagingServiceInstance( + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = LinkshorteningMessagingServiceInstance( self._version, payload, domain_sid=self._solution["domain_sid"], messaging_service_sid=self._solution["messaging_service_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -177,10 +287,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -189,12 +321,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py index 4c0b52bddf..1d88d07d0f 100644 --- a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -43,6 +44,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[ LinkshorteningMessagingServiceDomainAssociationContext ] = None @@ -82,6 +84,24 @@ async def fetch_async( """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,50 +135,98 @@ def __init__(self, version: Version, messaging_service_sid: str): ) ) - def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: + def _fetch(self) -> tuple: """ - Fetch the LinkshorteningMessagingServiceDomainAssociationInstance - + Internal helper for fetch operation - :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + payload, _, _ = self._fetch() return LinkshorteningMessagingServiceDomainAssociationInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def fetch_async( - self, - ) -> LinkshorteningMessagingServiceDomainAssociationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance and return response metadata - :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + payload, _, _ = await self._fetch_async() return LinkshorteningMessagingServiceDomainAssociationInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/request_managed_cert.py b/twilio/rest/messaging/v1/request_managed_cert.py index 81ccf9486c..227e36af9c 100644 --- a/twilio/rest/messaging/v1/request_managed_cert.py +++ b/twilio/rest/messaging/v1/request_managed_cert.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[RequestManagedCertContext] = None @property @@ -96,6 +98,24 @@ async def update_async(self) -> "RequestManagedCertInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the RequestManagedCertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the RequestManagedCertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -125,12 +145,12 @@ def __init__(self, version: Version, domain_sid: str): **self._solution ) - def update(self) -> RequestManagedCertInstance: + def _update(self) -> tuple: """ - Update the RequestManagedCertInstance - + Internal helper for update operation - :returns: The updated RequestManagedCertInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -138,20 +158,41 @@ def update(self) -> RequestManagedCertInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self) -> RequestManagedCertInstance: + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + payload, _, _ = self._update() return RequestManagedCertInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) - async def update_async(self) -> RequestManagedCertInstance: + def update_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to update the RequestManagedCertInstance + Update the RequestManagedCertInstance and return response metadata - :returns: The updated RequestManagedCertInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -159,14 +200,35 @@ async def update_async(self) -> RequestManagedCertInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self) -> RequestManagedCertInstance: + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + payload, _, _ = await self._update_async() return RequestManagedCertInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the RequestManagedCertInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/service/__init__.py b/twilio/rest/messaging/v1/service/__init__.py index 2ff3d4e191..d7da850830 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +23,9 @@ from twilio.base.page import Page from twilio.rest.messaging.v1.service.alpha_sender import AlphaSenderList from twilio.rest.messaging.v1.service.channel_sender import ChannelSenderList +from twilio.rest.messaging.v1.service.destination_alpha_sender import ( + DestinationAlphaSenderList, +) from twilio.rest.messaging.v1.service.phone_number import PhoneNumberList from twilio.rest.messaging.v1.service.short_code import ShortCodeList from twilio.rest.messaging.v1.service.us_app_to_person import UsAppToPersonList @@ -55,7 +59,7 @@ class ScanMessageContent(object): :ivar fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :ivar area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. :ivar synchronous_validation: Reserved. - :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :ivar url: The absolute URL of the Service resource. :ivar links: The absolute URLs of related resources. :ivar usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. @@ -111,6 +115,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -146,6 +151,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -164,6 +187,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -200,7 +241,7 @@ def update( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. @@ -262,7 +303,7 @@ async def update_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. @@ -288,6 +329,130 @@ async def update_async( use_inbound_webhook_on_number=use_inbound_webhook_on_number, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + @property def alpha_senders(self) -> AlphaSenderList: """ @@ -302,6 +467,13 @@ def channel_senders(self) -> ChannelSenderList: """ return self._proxy.channel_senders + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -359,11 +531,26 @@ def __init__(self, version: Version, sid: str): self._alpha_senders: Optional[AlphaSenderList] = None self._channel_senders: Optional[ChannelSenderList] = None + self._destination_alpha_senders: Optional[DestinationAlphaSenderList] = None self._phone_numbers: Optional[PhoneNumberList] = None self._short_codes: Optional[ShortCodeList] = None self._us_app_to_person: Optional[UsAppToPersonList] = None self._us_app_to_person_usecases: Optional[UsAppToPersonUsecaseList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -371,10 +558,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -383,56 +592,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, inbound_request_url: Union[str, object] = values.unset, @@ -452,28 +715,12 @@ def update( synchronous_validation: Union[bool, object] = values.unset, usecase: Union[str, object] = values.unset, use_inbound_webhook_on_number: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. - :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. - :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. - :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. - :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. - :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. - :param scan_message_content: - :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. - :param synchronous_validation: Reserved. - :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. - :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -508,13 +755,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, inbound_request_url: Union[str, object] = values.unset, @@ -536,7 +781,7 @@ async def update_async( use_inbound_webhook_on_number: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. @@ -550,24 +795,135 @@ async def update_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - data = values.of( - { - "FriendlyName": friendly_name, - "InboundRequestUrl": inbound_request_url, - "InboundMethod": inbound_method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StickySender": serialize.boolean_to_string(sticky_sender), - "MmsConverter": serialize.boolean_to_string(mms_converter), + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), "SmartEncoding": serialize.boolean_to_string(smart_encoding), "ScanMessageContent": scan_message_content, "FallbackToLongCode": serialize.boolean_to_string( @@ -590,12 +946,137 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def alpha_senders(self) -> AlphaSenderList: """ @@ -620,6 +1101,18 @@ def channel_senders(self) -> ChannelSenderList: ) return self._channel_senders + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -686,6 +1179,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -710,7 +1204,198 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( self, friendly_name: str, inbound_request_url: Union[str, object] = values.unset, @@ -730,28 +1415,12 @@ def create( synchronous_validation: Union[bool, object] = values.unset, usecase: Union[str, object] = values.unset, use_inbound_webhook_on_number: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. - :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. - :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. - :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. - :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. - :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. - :param scan_message_content: - :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. - :param synchronous_validation: Reserved. - :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. - :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + Internal async helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -786,12 +1455,10 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - async def create_async( self, friendly_name: str, @@ -828,51 +1495,96 @@ async def create_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "InboundRequestUrl": inbound_request_url, - "InboundMethod": inbound_method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StickySender": serialize.boolean_to_string(sticky_sender), - "MmsConverter": serialize.boolean_to_string(mms_converter), - "SmartEncoding": serialize.boolean_to_string(smart_encoding), - "ScanMessageContent": scan_message_content, - "FallbackToLongCode": serialize.boolean_to_string( - fallback_to_long_code - ), - "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), - "ValidityPeriod": validity_period, - "SynchronousValidation": serialize.boolean_to_string( - synchronous_validation - ), - "Usecase": usecase, - "UseInboundWebhookOnNumber": serialize.boolean_to_string( - use_inbound_webhook_on_number - ), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return ServiceInstance(self._version, payload) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def create_with_http_info_async( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata - headers["Accept"] = "application/json" + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, ) - - return ServiceInstance(self._version, payload) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -924,6 +1636,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -943,6 +1705,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -969,6 +1732,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -977,6 +1741,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1043,6 +1857,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/messaging/v1/service/alpha_sender.py b/twilio/rest/messaging/v1/service/alpha_sender.py index 2ba4c2a45c..2d91b12ebd 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AlphaSenderContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AlphaSenderInstance": """ Fetch the AlphaSenderInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "AlphaSenderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AlphaSenderInstance @@ -152,10 +204,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlphaSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -164,27 +238,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AlphaSenderInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AlphaSenderInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AlphaSenderInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlphaSenderInstance: + """ + Fetch the AlphaSenderInstance + + :returns: The fetched AlphaSenderInstance + """ + payload, _, _ = self._fetch() return AlphaSenderInstance( self._version, payload, @@ -192,22 +282,46 @@ def fetch(self) -> AlphaSenderInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AlphaSenderInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AlphaSenderInstance + Fetch the AlphaSenderInstance and return response metadata - :returns: The fetched AlphaSenderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AlphaSenderInstance: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + payload, _, _ = await self._fetch_async() return AlphaSenderInstance( self._version, payload, @@ -215,6 +329,22 @@ async def fetch_async(self) -> AlphaSenderInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -233,6 +363,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: :param payload: Payload response from the API """ + return AlphaSenderInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -264,13 +395,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) - def create(self, alpha_sender: str) -> AlphaSenderInstance: + def _create(self, alpha_sender: str) -> tuple: """ - Create the AlphaSenderInstance + Internal helper for create operation - :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. - - :returns: The created AlphaSenderInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -284,21 +414,43 @@ def create(self, alpha_sender: str) -> AlphaSenderInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + payload, _, _ = self._create(alpha_sender=alpha_sender) return AlphaSenderInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: + def create_with_http_info(self, alpha_sender: str) -> ApiResponse: """ - Asynchronously create the AlphaSenderInstance + Create the AlphaSenderInstance and return response metadata :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. - :returns: The created AlphaSenderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(alpha_sender=alpha_sender) + instance = AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, alpha_sender: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -312,14 +464,39 @@ async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Asynchronously create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + payload, _, _ = await self._create_async(alpha_sender=alpha_sender) return AlphaSenderInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, alpha_sender: str) -> ApiResponse: + """ + Asynchronously create the AlphaSenderInstance and return response metadata + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + alpha_sender=alpha_sender + ) + instance = AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -370,6 +547,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -389,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -415,6 +643,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -423,6 +652,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AlphaSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -454,7 +733,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AlphaSenderPage(self._version, response, self._solution) + return AlphaSenderPage(self._version, response, solution=self._solution) async def page_async( self, @@ -487,7 +766,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AlphaSenderPage(self._version, response, self._solution) + return AlphaSenderPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlphaSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AlphaSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlphaSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AlphaSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AlphaSenderPage: """ @@ -499,7 +848,7 @@ def get_page(self, target_url: str) -> AlphaSenderPage: :returns: Page of AlphaSenderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AlphaSenderPage(self._version, response, self._solution) + return AlphaSenderPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AlphaSenderPage: """ @@ -511,7 +860,7 @@ async def get_page_async(self, target_url: str) -> AlphaSenderPage: :returns: Page of AlphaSenderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AlphaSenderPage(self._version, response, self._solution) + return AlphaSenderPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AlphaSenderContext: """ diff --git a/twilio/rest/messaging/v1/service/channel_sender.py b/twilio/rest/messaging/v1/service/channel_sender.py index 9d708a2fba..37a8f4d9a5 100644 --- a/twilio/rest/messaging/v1/service/channel_sender.py +++ b/twilio/rest/messaging/v1/service/channel_sender.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "messaging_service_sid": messaging_service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelSenderContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelSenderInstance": """ Fetch the ChannelSenderInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "ChannelSenderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -147,6 +185,20 @@ def __init__(self, version: Version, messaging_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelSenderInstance @@ -154,10 +206,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -166,27 +240,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ChannelSenderInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ChannelSenderInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ChannelSenderInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelSenderInstance: + """ + Fetch the ChannelSenderInstance + + :returns: The fetched ChannelSenderInstance + """ + payload, _, _ = self._fetch() return ChannelSenderInstance( self._version, payload, @@ -194,22 +284,46 @@ def fetch(self) -> ChannelSenderInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChannelSenderInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChannelSenderInstance + Fetch the ChannelSenderInstance and return response metadata - :returns: The fetched ChannelSenderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChannelSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + payload, _, _ = await self._fetch_async() return ChannelSenderInstance( self._version, payload, @@ -217,6 +331,22 @@ async def fetch_async(self) -> ChannelSenderInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +365,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelSenderInstance: :param payload: Payload response from the API """ + return ChannelSenderInstance( self._version, payload, @@ -270,13 +401,12 @@ def __init__(self, version: Version, messaging_service_sid: str): **self._solution ) - def create(self, sid: str) -> ChannelSenderInstance: + def _create(self, sid: str) -> tuple: """ - Create the ChannelSenderInstance - - :param sid: The SID of the Channel Sender being added to the Service. + Internal helper for create operation - :returns: The created ChannelSenderInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -290,23 +420,47 @@ def create(self, sid: str) -> ChannelSenderInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, sid: str) -> ChannelSenderInstance: + """ + Create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + payload, _, _ = self._create(sid=sid) return ChannelSenderInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def create_async(self, sid: str) -> ChannelSenderInstance: + def create_with_http_info(self, sid: str) -> ApiResponse: """ - Asynchronously create the ChannelSenderInstance + Create the ChannelSenderInstance and return response metadata :param sid: The SID of the Channel Sender being added to the Service. - :returns: The created ChannelSenderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(sid=sid) + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -320,16 +474,41 @@ async def create_async(self, sid: str) -> ChannelSenderInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, sid: str) -> ChannelSenderInstance: + """ + Asynchronously create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + payload, _, _ = await self._create_async(sid=sid) return ChannelSenderInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def create_with_http_info_async(self, sid: str) -> ApiResponse: + """ + Asynchronously create the ChannelSenderInstance and return response metadata + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(sid=sid) + instance = ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -380,6 +559,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -399,6 +628,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -425,6 +655,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -433,6 +664,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -464,7 +745,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) async def page_async( self, @@ -497,7 +778,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelSenderPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelSenderPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChannelSenderPage: """ @@ -509,7 +860,7 @@ def get_page(self, target_url: str) -> ChannelSenderPage: :returns: Page of ChannelSenderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelSenderPage: """ @@ -521,7 +872,7 @@ async def get_page_async(self, target_url: str) -> ChannelSenderPage: :returns: Page of ChannelSenderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelSenderContext: """ diff --git a/twilio/rest/messaging/v1/service/destination_alpha_sender.py b/twilio/rest/messaging/v1/service/destination_alpha_sender.py new file mode 100644 index 0000000000..4b8194b368 --- /dev/null +++ b/twilio/rest/messaging/v1/service/destination_alpha_sender.py @@ -0,0 +1,969 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DestinationAlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + :ivar iso_country_code: The Two Character ISO Country Code the Alphanumeric Sender ID will be used for. For Default Alpha Senders that work across countries, this value will be an empty string + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.iso_country_code: Optional[str] = payload.get("iso_country_code") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[DestinationAlphaSenderContext] = None + + @property + def _proxy(self) -> "DestinationAlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DestinationAlphaSenderContext for this DestinationAlphaSenderInstance + """ + if self._context is None: + self._context = DestinationAlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "DestinationAlphaSenderInstance": + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DestinationAlphaSenderInstance": + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DestinationAlphaSenderInstance {}>".format(context) + + +class DestinationAlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the DestinationAlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders/{sid}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DestinationAlphaSenderInstance: + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + payload, _, _ = self._fetch() + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DestinationAlphaSenderInstance: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + payload, _, _ = await self._fetch_async() + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DestinationAlphaSenderContext {}>".format(context) + + +class DestinationAlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DestinationAlphaSenderInstance: + """ + Build an instance of DestinationAlphaSenderInstance + + :param payload: Payload response from the API + """ + + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DestinationAlphaSenderPage>" + + +class DestinationAlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DestinationAlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders".format( + **self._solution + ) + + def _create( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + payload, _, _ = self._create( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the DestinationAlphaSenderInstance and return response metadata + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + instance = DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Asynchronously create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + payload, _, _ = await self._create_async( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the DestinationAlphaSenderInstance and return response metadata + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + alpha_sender=alpha_sender, iso_country_code=iso_country_code + ) + instance = DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DestinationAlphaSenderInstance]: + """ + Streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DestinationAlphaSenderInstance]: + """ + Asynchronously streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DestinationAlphaSenderInstance and returns headers from first page + + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DestinationAlphaSenderInstance and returns headers from first page + + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Asynchronously lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DestinationAlphaSenderInstance and returns headers from first page + + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DestinationAlphaSenderInstance and returns headers from first page + + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + + async def page_async( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DestinationAlphaSenderPage, status code, and headers + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DestinationAlphaSenderPage, status code, and headers + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DestinationAlphaSenderPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DestinationAlphaSenderList>" diff --git a/twilio/rest/messaging/v1/service/phone_number.py b/twilio/rest/messaging/v1/service/phone_number.py index 11b806583e..9992fd0102 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -147,6 +185,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -154,10 +206,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -166,27 +240,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PhoneNumberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PhoneNumberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() return PhoneNumberInstance( self._version, payload, @@ -194,22 +284,46 @@ def fetch(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> PhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return PhoneNumberInstance( self._version, payload, @@ -217,6 +331,22 @@ async def fetch_async(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +365,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -266,13 +397,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - def create(self, phone_number_sid: str) -> PhoneNumberInstance: + def _create(self, phone_number_sid: str) -> tuple: """ - Create the PhoneNumberInstance + Internal helper for create operation - :param phone_number_sid: The SID of the Phone Number being added to the Service. - - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -286,21 +416,43 @@ def create(self, phone_number_sid: str) -> PhoneNumberInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = self._create(phone_number_sid=phone_number_sid) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + def create_with_http_info(self, phone_number_sid: str) -> ApiResponse: """ - Asynchronously create the PhoneNumberInstance + Create the PhoneNumberInstance and return response metadata :param phone_number_sid: The SID of the Phone Number being added to the Service. - :returns: The created PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number_sid=phone_number_sid) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -314,14 +466,39 @@ async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = await self._create_async(phone_number_sid=phone_number_sid) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, phone_number_sid: str) -> ApiResponse: + """ + Asynchronously create the PhoneNumberInstance and return response metadata + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number_sid=phone_number_sid + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -372,6 +549,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -391,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -417,6 +645,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -425,6 +654,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -456,7 +735,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -489,7 +768,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PhoneNumberPage: """ @@ -501,7 +850,7 @@ def get_page(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ @@ -513,7 +862,7 @@ async def get_page_async(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PhoneNumberContext: """ diff --git a/twilio/rest/messaging/v1/service/short_code.py b/twilio/rest/messaging/v1/service/short_code.py index 172c78dbb9..f1e7039dfc 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ShortCodeInstance": """ Fetch the ShortCodeInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "ShortCodeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ShortCodeInstance @@ -152,10 +204,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ShortCodeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -164,27 +238,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ShortCodeInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ShortCodeInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ShortCodeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = self._fetch() return ShortCodeInstance( self._version, payload, @@ -192,22 +282,46 @@ def fetch(self) -> ShortCodeInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ShortCodeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ShortCodeInstance + Fetch the ShortCodeInstance and return response metadata - :returns: The fetched ShortCodeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + payload, _, _ = await self._fetch_async() return ShortCodeInstance( self._version, payload, @@ -215,6 +329,22 @@ async def fetch_async(self) -> ShortCodeInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -233,6 +363,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: :param payload: Payload response from the API """ + return ShortCodeInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -264,13 +395,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) - def create(self, short_code_sid: str) -> ShortCodeInstance: + def _create(self, short_code_sid: str) -> tuple: """ - Create the ShortCodeInstance + Internal helper for create operation - :param short_code_sid: The SID of the ShortCode resource being added to the Service. - - :returns: The created ShortCodeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -284,21 +414,43 @@ def create(self, short_code_sid: str) -> ShortCodeInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, short_code_sid: str) -> ShortCodeInstance: + """ + Create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + payload, _, _ = self._create(short_code_sid=short_code_sid) return ShortCodeInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, short_code_sid: str) -> ShortCodeInstance: + def create_with_http_info(self, short_code_sid: str) -> ApiResponse: """ - Asynchronously create the ShortCodeInstance + Create the ShortCodeInstance and return response metadata :param short_code_sid: The SID of the ShortCode resource being added to the Service. - :returns: The created ShortCodeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(short_code_sid=short_code_sid) + instance = ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, short_code_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -312,14 +464,39 @@ async def create_async(self, short_code_sid: str) -> ShortCodeInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, short_code_sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + payload, _, _ = await self._create_async(short_code_sid=short_code_sid) return ShortCodeInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, short_code_sid: str) -> ApiResponse: + """ + Asynchronously create the ShortCodeInstance and return response metadata + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + short_code_sid=short_code_sid + ) + instance = ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -370,6 +547,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -389,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -415,6 +643,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -423,6 +652,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ShortCodeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -454,7 +733,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) async def page_async( self, @@ -487,7 +766,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ShortCodePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ShortCodePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ShortCodePage: """ @@ -499,7 +848,7 @@ def get_page(self, target_url: str) -> ShortCodePage: :returns: Page of ShortCodeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ShortCodePage: """ @@ -511,7 +860,7 @@ async def get_page_async(self, target_url: str) -> ShortCodePage: :returns: Page of ShortCodeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ShortCodePage(self._version, response, self._solution) + return ShortCodePage(self._version, response, solution=self._solution) def get(self, sid: str) -> ShortCodeContext: """ diff --git a/twilio/rest/messaging/v1/service/us_app_to_person.py b/twilio/rest/messaging/v1/service/us_app_to_person.py index dd451f5c59..ba3bfdc125 100644 --- a/twilio/rest/messaging/v1/service/us_app_to_person.py +++ b/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,8 @@ class UsAppToPersonInstance(InstanceResource): :ivar url: The absolute URL of the US App to Person resource. :ivar mock: A boolean that specifies whether campaign is a mock or not. Mock campaigns will be automatically created if using a mock brand. Mock campaigns should only be used for testing purposes. :ivar errors: Details indicating why a campaign registration failed. These errors can indicate one or more fields that were incorrect or did not meet review requirements. + :ivar privacy_policy_url: The URL of the privacy policy for the campaign. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the campaign. """ def __init__( @@ -101,11 +104,16 @@ def __init__( self.url: Optional[str] = payload.get("url") self.mock: Optional[bool] = payload.get("mock") self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) self._solution = { "messaging_service_sid": messaging_service_sid, "sid": sid or self.sid, } + self._context: Optional[UsAppToPersonContext] = None @property @@ -142,23 +150,79 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() - def fetch(self) -> "UsAppToPersonInstance": + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": """ Fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request :returns: The fetched UsAppToPersonInstance """ - return self._proxy.fetch() + return self._proxy.fetch( + x_twilio_api_version=x_twilio_api_version, + ) - async def fetch_async(self) -> "UsAppToPersonInstance": + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": """ Asynchronous coroutine to fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request :returns: The fetched UsAppToPersonInstance """ - return await self._proxy.fetch_async() + return await self._proxy.fetch_async( + x_twilio_api_version=x_twilio_api_version, + ) + + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + x_twilio_api_version=x_twilio_api_version, + ) + + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, + ) def update( self, @@ -169,6 +233,9 @@ def update( description: str, age_gated: bool, direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, ) -> "UsAppToPersonInstance": """ Update the UsAppToPersonInstance @@ -180,6 +247,9 @@ def update( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. :returns: The updated UsAppToPersonInstance """ @@ -191,6 +261,9 @@ def update( description=description, age_gated=age_gated, direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, ) async def update_async( @@ -202,6 +275,9 @@ async def update_async( description: str, age_gated: bool, direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, ) -> "UsAppToPersonInstance": """ Asynchronous coroutine to update the UsAppToPersonInstance @@ -213,6 +289,9 @@ async def update_async( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. :returns: The updated UsAppToPersonInstance """ @@ -224,6 +303,93 @@ async def update_async( description=description, age_gated=age_gated, direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + def update_with_http_info( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UsAppToPersonInstance with HTTP info + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + async def update_with_http_info_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UsAppToPersonInstance with HTTP info + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, ) def __repr__(self) -> str: @@ -257,6 +423,20 @@ def __init__(self, version: Version, messaging_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UsAppToPersonInstance @@ -264,10 +444,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UsAppToPersonInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -276,27 +478,52 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> UsAppToPersonInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the UsAppToPersonInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self, x_twilio_api_version: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched UsAppToPersonInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> UsAppToPersonInstance: + """ + Fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + payload, _, _ = self._fetch(x_twilio_api_version=x_twilio_api_version) return UsAppToPersonInstance( self._version, payload, @@ -304,22 +531,64 @@ def fetch(self) -> UsAppToPersonInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> UsAppToPersonInstance: + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the UsAppToPersonInstance + Fetch the UsAppToPersonInstance and return response metadata + :param x_twilio_api_version: The version of the Messaging API to use for this request - :returns: The fetched UsAppToPersonInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: The fetched UsAppToPersonInstance + """ + payload, _, _ = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version + ) return UsAppToPersonInstance( self._version, payload, @@ -327,7 +596,28 @@ async def fetch_async(self) -> UsAppToPersonInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance and return response metadata + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, has_embedded_links: bool, has_embedded_phone: bool, @@ -336,19 +626,15 @@ def update( description: str, age_gated: bool, direct_lending: bool, - ) -> UsAppToPersonInstance: + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: """ - Update the UsAppToPersonInstance - - :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. - :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. - :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. - :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. - :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. - :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. - :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + Internal helper for update operation - :returns: The updated UsAppToPersonInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -360,18 +646,67 @@ def update( "Description": description, "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, } ) headers = values.of({}) + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The updated UsAppToPersonInstance + """ + payload, _, _ = self._update( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) return UsAppToPersonInstance( self._version, payload, @@ -379,7 +714,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, has_embedded_links: bool, has_embedded_phone: bool, @@ -388,9 +723,12 @@ async def update_async( description: str, age_gated: bool, direct_lending: bool, - ) -> UsAppToPersonInstance: + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to update the UsAppToPersonInstance + Update the UsAppToPersonInstance and return response metadata :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. @@ -399,8 +737,50 @@ async def update_async( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. - :returns: The updated UsAppToPersonInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -412,43 +792,142 @@ async def update_async( "Description": description, "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, } ) headers = values.of({}) + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return UsAppToPersonInstance( - self._version, - payload, - messaging_service_sid=self._solution["messaging_service_sid"], - sid=self._solution["sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + async def update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> UsAppToPersonInstance: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Messaging.V1.UsAppToPersonContext {}>".format(context) - - -class UsAppToPersonPage(Page): + Asynchronous coroutine to update the UsAppToPersonInstance - def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The updated UsAppToPersonInstance + """ + payload, _, _ = await self._update_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UsAppToPersonInstance and return response metadata + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.UsAppToPersonContext {}>".format(context) + + +class UsAppToPersonPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: """ Build an instance of UsAppToPersonInstance :param payload: Payload response from the API """ + return UsAppToPersonInstance( self._version, payload, @@ -484,7 +963,7 @@ def __init__(self, version: Version, messaging_service_sid: str): **self._solution ) - def create( + def _create( self, brand_registration_sid: str, description: str, @@ -493,6 +972,7 @@ def create( us_app_to_person_usecase: str, has_embedded_links: bool, has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, opt_in_message: Union[str, object] = values.unset, opt_out_message: Union[str, object] = values.unset, help_message: Union[str, object] = values.unset, @@ -502,28 +982,14 @@ def create( subscriber_opt_in: Union[bool, object] = values.unset, age_gated: Union[bool, object] = values.unset, direct_lending: Union[bool, object] = values.unset, - ) -> UsAppToPersonInstance: + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: """ - Create the UsAppToPersonInstance - - :param brand_registration_sid: A2P Brand Registration SID - :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. - :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. - :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. - :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] - :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. - :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. - :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. - :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. - :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. - :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. - :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. - :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. - :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. - :param age_gated: A boolean that specifies whether campaign is age gated or not. - :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + Internal helper for create operation - :returns: The created UsAppToPersonInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -544,25 +1010,100 @@ def create( "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The created UsAppToPersonInstance + """ + payload, _, _ = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) return UsAppToPersonInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def create_async( + def create_with_http_info( self, brand_registration_sid: str, description: str, @@ -571,6 +1112,7 @@ async def create_async( us_app_to_person_usecase: str, has_embedded_links: bool, has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, opt_in_message: Union[str, object] = values.unset, opt_out_message: Union[str, object] = values.unset, help_message: Union[str, object] = values.unset, @@ -580,9 +1122,11 @@ async def create_async( subscriber_opt_in: Union[bool, object] = values.unset, age_gated: Union[bool, object] = values.unset, direct_lending: Union[bool, object] = values.unset, - ) -> UsAppToPersonInstance: + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the UsAppToPersonInstance + Create the UsAppToPersonInstance and return response metadata :param brand_registration_sid: A2P Brand Registration SID :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. @@ -591,6 +1135,7 @@ async def create_async( :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. @@ -600,8 +1145,66 @@ async def create_async( :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. :param age_gated: A boolean that specifies whether campaign is age gated or not. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. - :returns: The created UsAppToPersonInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -622,26 +1225,177 @@ async def create_async( "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + } + ) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Asynchronously create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The created UsAppToPersonInstance + """ + payload, _, _ = await self._create_async( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) return UsAppToPersonInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def create_with_http_info_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UsAppToPersonInstance and return response metadata + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, + x_twilio_api_version: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[UsAppToPersonInstance]: @@ -651,6 +1405,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str x_twilio_api_version: The version of the Messaging API to use for this request :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -661,12 +1416,15 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) + page = self.page( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) return self._version.stream(page, limits["limit"]) async def stream_async( self, + x_twilio_api_version: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[UsAppToPersonInstance]: @@ -676,6 +1434,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str x_twilio_api_version: The version of the Messaging API to use for this request :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -686,12 +1445,71 @@ async def stream_async( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) + page = await self.page_async( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, + x_twilio_api_version: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[UsAppToPersonInstance]: @@ -700,6 +1518,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str x_twilio_api_version: The version of the Messaging API to use for this request :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -709,8 +1528,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + x_twilio_api_version=x_twilio_api_version, limit=limit, page_size=page_size, ) @@ -718,6 +1539,7 @@ def list( async def list_async( self, + x_twilio_api_version: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[UsAppToPersonInstance]: @@ -726,6 +1548,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str x_twilio_api_version: The version of the Messaging API to use for this request :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -735,16 +1558,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + x_twilio_api_version=x_twilio_api_version, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsAppToPersonInstance and returns headers from first page + + + :param str x_twilio_api_version: The version of the Messaging API to use for this request + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, + x_twilio_api_version: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -753,6 +1635,7 @@ def page( Retrieve a single page of UsAppToPersonInstance records from the API. Request is executed immediately + :param x_twilio_api_version: The version of the Messaging API to use for this request :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -761,23 +1644,30 @@ def page( """ data = values.of( { + "X-Twilio-Api-Version": x_twilio_api_version, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) headers["Accept"] = "application/json" response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UsAppToPersonPage(self._version, response, self._solution) + return UsAppToPersonPage(self._version, response, solution=self._solution) async def page_async( self, + x_twilio_api_version: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -786,6 +1676,7 @@ async def page_async( Asynchronously retrieve a single page of UsAppToPersonInstance records from the API. Request is executed immediately + :param x_twilio_api_version: The version of the Messaging API to use for this request :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -794,20 +1685,112 @@ async def page_async( """ data = values.of( { + "X-Twilio-Api-Version": x_twilio_api_version, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) headers["Accept"] = "application/json" response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UsAppToPersonPage(self._version, response, self._solution) + return UsAppToPersonPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + x_twilio_api_version: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsAppToPersonPage, status code, and headers + """ + data = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsAppToPersonPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + x_twilio_api_version: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsAppToPersonPage, status code, and headers + """ + data = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsAppToPersonPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UsAppToPersonPage: """ @@ -819,7 +1802,7 @@ def get_page(self, target_url: str) -> UsAppToPersonPage: :returns: Page of UsAppToPersonInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UsAppToPersonPage(self._version, response, self._solution) + return UsAppToPersonPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UsAppToPersonPage: """ @@ -831,7 +1814,7 @@ async def get_page_async(self, target_url: str) -> UsAppToPersonPage: :returns: Page of UsAppToPersonInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UsAppToPersonPage(self._version, response, self._solution) + return UsAppToPersonPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UsAppToPersonContext: """ diff --git a/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py index bf9e48e626..76ab18b76c 100644 --- a/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py +++ b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,14 +71,14 @@ def __init__(self, version: Version, messaging_service_sid: str): ) ) - def fetch( + def _fetch( self, brand_registration_sid: Union[str, object] = values.unset - ) -> UsAppToPersonUsecaseInstance: + ) -> tuple: """ - Asynchronously fetch the UsAppToPersonUsecaseInstance + Internal helper for fetch operation - :param brand_registration_sid: The unique string to identify the A2P brand. - :returns: The fetched UsAppToPersonUsecaseInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -89,24 +90,53 @@ def fetch( } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) + def fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + payload, _, _ = self._fetch(brand_registration_sid=brand_registration_sid) return UsAppToPersonUsecaseInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, brand_registration_sid: Union[str, object] = values.unset - ) -> UsAppToPersonUsecaseInstance: + ) -> ApiResponse: """ - Asynchronously fetch the UsAppToPersonUsecaseInstance + Fetch the UsAppToPersonUsecaseInstance and return response metadata :param brand_registration_sid: The unique string to identify the A2P brand. - :returns: The fetched UsAppToPersonUsecaseInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -118,16 +148,47 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + payload, _, _ = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) return UsAppToPersonUsecaseInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def fetch_with_http_info_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance and return response metadata + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/tollfree_verification.py b/twilio/rest/messaging/v1/tollfree_verification.py index d052bd4cde..844e16054e 100644 --- a/twilio/rest/messaging/v1/tollfree_verification.py +++ b/twilio/rest/messaging/v1/tollfree_verification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +25,33 @@ class TollfreeVerificationInstance(InstanceResource): + class BusinessRegistrationAuthority(object): + EIN = "EIN" + CBN = "CBN" + CRN = "CRN" + PROVINCIAL_NUMBER = "PROVINCIAL_NUMBER" + VAT = "VAT" + ACN = "ACN" + ABN = "ABN" + BRN = "BRN" + SIREN = "SIREN" + SIRET = "SIRET" + NZBN = "NZBN" + UST_IDNR = "USt-IdNr" + CIF = "CIF" + NIF = "NIF" + CNPJ = "CNPJ" + UID = "UID" + NEQ = "NEQ" + OTHER = "OTHER" + + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + NON_PROFIT = "NON_PROFIT" + GOVERNMENT = "GOVERNMENT" + class OptInType(object): VERBAL = "VERBAL" WEB_FORM = "WEB_FORM" @@ -31,6 +59,7 @@ class OptInType(object): VIA_TEXT = "VIA_TEXT" MOBILE_QR_CODE = "MOBILE_QR_CODE" IMPORT = "IMPORT" + IMPORT_PLEASE_REPLACE = "IMPORT_PLEASE_REPLACE" class Status(object): PENDING_REVIEW = "PENDING_REVIEW" @@ -38,6 +67,9 @@ class Status(object): TWILIO_APPROVED = "TWILIO_APPROVED" TWILIO_REJECTED = "TWILIO_REJECTED" + class VettingProvider(object): + CAMPAIGN_VERIFY = "CAMPAIGN_VERIFY" + """ :ivar sid: The unique string to identify Tollfree Verification. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tollfree Verification resource. @@ -59,7 +91,7 @@ class Status(object): :ivar business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :ivar business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :ivar notification_email: The email address to receive the notification about the verification result. . - :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :ivar use_case_summary: Use this to further explain how messaging is used by the business or organization. :ivar production_message_sample: An example of message content, i.e. a sample message. :ivar opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -67,15 +99,31 @@ class Status(object): :ivar message_volume: Estimate monthly volume of messages from the Tollfree Number. :ivar additional_information: Additional information to be provided for verification. :ivar tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :ivar tollfree_phone_number: The E.164 formatted toll-free phone number associated with the verification. :ivar status: :ivar url: The absolute URL of the Tollfree Verification resource. :ivar rejection_reason: The rejection reason given when a Tollfree Verification has been rejected. :ivar error_code: The error code given when a Tollfree Verification has been rejected. :ivar edit_expiration: The date and time when the ability to edit a rejected verification expires. :ivar edit_allowed: If a rejected verification is allowed to be edited/resubmitted. Some rejection reasons allow editing and some do not. + :ivar business_registration_number: A legally recognized business registration number + :ivar business_registration_authority: + :ivar business_registration_country: Country business is registered in + :ivar business_type: + :ivar business_registration_phone_number: The E.164 formatted number associated with the business. + :ivar doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :ivar opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :ivar help_message_sample: A sample help message provided to users. + :ivar privacy_policy_url: The URL to the privacy policy for the business or organization. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the business or organization. + :ivar age_gated_content: Indicates if the content is age gated. + :ivar opt_in_keywords: List of keywords that users can send to opt in or out of messages. :ivar rejection_reasons: A list of rejection reasons and codes describing why a Tollfree Verification has been rejected. :ivar resource_links: The URLs of the documents associated with the Tollfree Verification resource. :ivar external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :ivar vetting_id: + :ivar vetting_provider: + :ivar vetting_id_expiration: """ def __init__( @@ -121,8 +169,8 @@ def __init__( "business_contact_phone" ) self.notification_email: Optional[str] = payload.get("notification_email") - self.use_case_categories: Optional[List[str]] = payload.get( - "use_case_categories" + self.use_case_categories: Optional["TollfreeVerificationInstance.str]"] = ( + payload.get("use_case_categories") ) self.use_case_summary: Optional[str] = payload.get("use_case_summary") self.production_message_sample: Optional[str] = payload.get( @@ -139,6 +187,7 @@ def __init__( self.tollfree_phone_number_sid: Optional[str] = payload.get( "tollfree_phone_number_sid" ) + self.tollfree_phone_number: Optional[str] = payload.get("tollfree_phone_number") self.status: Optional["TollfreeVerificationInstance.Status"] = payload.get( "status" ) @@ -149,15 +198,49 @@ def __init__( payload.get("edit_expiration") ) self.edit_allowed: Optional[bool] = payload.get("edit_allowed") + self.business_registration_number: Optional[str] = payload.get( + "business_registration_number" + ) + self.business_registration_authority: Optional[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority" + ] = payload.get("business_registration_authority") + self.business_registration_country: Optional[str] = payload.get( + "business_registration_country" + ) + self.business_type: Optional["TollfreeVerificationInstance.BusinessType"] = ( + payload.get("business_type") + ) + self.business_registration_phone_number: Optional[str] = payload.get( + "business_registration_phone_number" + ) + self.doing_business_as: Optional[str] = payload.get("doing_business_as") + self.opt_in_confirmation_message: Optional[str] = payload.get( + "opt_in_confirmation_message" + ) + self.help_message_sample: Optional[str] = payload.get("help_message_sample") + self.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) + self.age_gated_content: Optional[bool] = payload.get("age_gated_content") + self.opt_in_keywords: Optional[List[str]] = payload.get("opt_in_keywords") self.rejection_reasons: Optional[List[Dict[str, object]]] = payload.get( "rejection_reasons" ) self.resource_links: Optional[Dict[str, object]] = payload.get("resource_links") self.external_reference_id: Optional[str] = payload.get("external_reference_id") + self.vetting_id: Optional[str] = payload.get("vetting_id") + self.vetting_provider: Optional[ + "TollfreeVerificationInstance.VettingProvider" + ] = payload.get("vetting_provider") + self.vetting_id_expiration: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("vetting_id_expiration") + ) self._solution = { "sid": sid or self.sid, } + self._context: Optional[TollfreeVerificationContext] = None @property @@ -193,6 +276,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TollfreeVerificationInstance": """ Fetch the TollfreeVerificationInstance @@ -211,6 +312,24 @@ async def fetch_async(self) -> "TollfreeVerificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, business_name: Union[str, object] = values.unset, @@ -236,6 +355,26 @@ def update( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> "TollfreeVerificationInstance": """ Update the TollfreeVerificationInstance @@ -243,7 +382,7 @@ def update( :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -261,6 +400,20 @@ def update( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The updated TollfreeVerificationInstance """ @@ -286,6 +439,20 @@ def update( business_contact_email=business_contact_email, business_contact_phone=business_contact_phone, edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) async def update_async( @@ -313,6 +480,26 @@ async def update_async( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> "TollfreeVerificationInstance": """ Asynchronous coroutine to update the TollfreeVerificationInstance @@ -320,7 +507,7 @@ async def update_async( :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -338,6 +525,20 @@ async def update_async( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The updated TollfreeVerificationInstance """ @@ -363,6 +564,270 @@ async def update_async( business_contact_email=business_contact_email, business_contact_phone=business_contact_phone, edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + + def update_with_http_info( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TollfreeVerificationInstance with HTTP info + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + + async def update_with_http_info_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance with HTTP info + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) def __repr__(self) -> str: @@ -392,6 +857,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Tollfree/Verifications/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TollfreeVerificationInstance @@ -399,10 +878,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -411,56 +912,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TollfreeVerificationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TollfreeVerificationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TollfreeVerificationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TollfreeVerificationInstance: + """ + Fetch the TollfreeVerificationInstance + + :returns: The fetched TollfreeVerificationInstance + """ + payload, _, _ = self._fetch() return TollfreeVerificationInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> TollfreeVerificationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TollfreeVerificationInstance + Fetch the TollfreeVerificationInstance and return response metadata - :returns: The fetched TollfreeVerificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + payload, _, _ = await self._fetch_async() return TollfreeVerificationInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, @@ -485,33 +1040,32 @@ def update( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, - ) -> TollfreeVerificationInstance: + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: """ - Update the TollfreeVerificationInstance + Internal helper for update operation - :param business_name: The name of the business or organization using the Tollfree number. - :param business_website: The website of the business or organization using the Tollfree number. - :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. - :param use_case_summary: Use this to further explain how messaging is used by the business or organization. - :param production_message_sample: An example of message content, i.e. a sample message. - :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. - :param opt_in_type: - :param message_volume: Estimate monthly volume of messages from the Tollfree Number. - :param business_street_address: The address of the business or organization using the Tollfree number. - :param business_street_address2: The address of the business or organization using the Tollfree number. - :param business_city: The city of the business or organization using the Tollfree number. - :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. - :param business_postal_code: The postal code of the business or organization using the Tollfree number. - :param business_country: The country of the business or organization using the Tollfree number. - :param additional_information: Additional information to be provided for verification. - :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. - :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. - :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. - :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. - :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. - - :returns: The updated TollfreeVerificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -537,6 +1091,20 @@ def update( "BusinessContactEmail": business_contact_email, "BusinessContactPhone": business_contact_phone, "EditReason": edit_reason, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, } ) headers = values.of({}) @@ -545,15 +1113,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TollfreeVerificationInstance( - self._version, payload, sid=self._solution["sid"] - ) - - async def update_async( + def update( self, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, @@ -578,14 +1142,34 @@ async def update_async( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> TollfreeVerificationInstance: """ - Asynchronous coroutine to update the TollfreeVerificationInstance + Update the TollfreeVerificationInstance :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -603,104 +1187,77 @@ async def update_async( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The updated TollfreeVerificationInstance """ - - data = values.of( - { - "BusinessName": business_name, - "BusinessWebsite": business_website, - "NotificationEmail": notification_email, - "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), - "UseCaseSummary": use_case_summary, - "ProductionMessageSample": production_message_sample, - "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), - "OptInType": opt_in_type, - "MessageVolume": message_volume, - "BusinessStreetAddress": business_street_address, - "BusinessStreetAddress2": business_street_address2, - "BusinessCity": business_city, - "BusinessStateProvinceRegion": business_state_province_region, - "BusinessPostalCode": business_postal_code, - "BusinessCountry": business_country, - "AdditionalInformation": additional_information, - "BusinessContactFirstName": business_contact_first_name, - "BusinessContactLastName": business_contact_last_name, - "BusinessContactEmail": business_contact_email, - "BusinessContactPhone": business_contact_phone, - "EditReason": edit_reason, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) - return TollfreeVerificationInstance( self._version, payload, sid=self._solution["sid"] ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Messaging.V1.TollfreeVerificationContext {}>".format(context) - - -class TollfreeVerificationPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: - """ - Build an instance of TollfreeVerificationInstance - - :param payload: Payload response from the API - """ - return TollfreeVerificationInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Messaging.V1.TollfreeVerificationPage>" - - -class TollfreeVerificationList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the TollfreeVerificationList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Tollfree/Verifications" - - def create( + def update_with_http_info( self, - business_name: str, - business_website: str, - notification_email: str, - use_case_categories: List[str], - use_case_summary: str, - production_message_sample: str, - opt_in_image_urls: List[str], - opt_in_type: "TollfreeVerificationInstance.OptInType", - message_volume: str, - tollfree_phone_number_sid: str, - customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, business_street_address: Union[str, object] = values.unset, business_street_address2: Union[str, object] = values.unset, business_city: Union[str, object] = values.unset, @@ -712,22 +1269,40 @@ def create( business_contact_last_name: Union[str, object] = values.unset, business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, - external_reference_id: Union[str, object] = values.unset, - ) -> TollfreeVerificationInstance: + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Create the TollfreeVerificationInstance + Update the TollfreeVerificationInstance and return response metadata :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. :param opt_in_type: :param message_volume: Estimate monthly volume of messages from the Tollfree Number. - :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. - :param customer_profile_sid: Customer's Profile Bundle BundleSid. :param business_street_address: The address of the business or organization using the Tollfree number. :param business_street_address2: The address of the business or organization using the Tollfree number. :param business_city: The city of the business or organization using the Tollfree number. @@ -739,9 +1314,117 @@ def create( :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. - :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The created TollfreeVerificationInstance + async def _update_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -755,8 +1438,6 @@ def create( "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), "OptInType": opt_in_type, "MessageVolume": message_volume, - "TollfreePhoneNumberSid": tollfree_phone_number_sid, - "CustomerProfileSid": customer_profile_sid, "BusinessStreetAddress": business_street_address, "BusinessStreetAddress2": business_street_address2, "BusinessCity": business_city, @@ -768,34 +1449,46 @@ def create( "BusinessContactLastName": business_contact_last_name, "BusinessContactEmail": business_contact_email, "BusinessContactPhone": business_contact_phone, - "ExternalReferenceId": external_reference_id, + "EditReason": edit_reason, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of({}) headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return TollfreeVerificationInstance(self._version, payload) - - async def create_async( + async def update_async( self, - business_name: str, - business_website: str, - notification_email: str, - use_case_categories: List[str], - use_case_summary: str, - production_message_sample: str, - opt_in_image_urls: List[str], - opt_in_type: "TollfreeVerificationInstance.OptInType", - message_volume: str, - tollfree_phone_number_sid: str, - customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, business_street_address: Union[str, object] = values.unset, business_street_address2: Union[str, object] = values.unset, business_city: Union[str, object] = values.unset, @@ -807,22 +1500,40 @@ async def create_async( business_contact_last_name: Union[str, object] = values.unset, business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, - external_reference_id: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> TollfreeVerificationInstance: """ - Asynchronously create the TollfreeVerificationInstance + Asynchronous coroutine to update the TollfreeVerificationInstance :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. :param opt_in_type: :param message_volume: Estimate monthly volume of messages from the Tollfree Number. - :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. - :param customer_profile_sid: Customer's Profile Bundle BundleSid. :param business_street_address: The address of the business or organization using the Tollfree number. :param business_street_address2: The address of the business or organization using the Tollfree number. :param business_city: The city of the business or organization using the Tollfree number. @@ -834,9 +1545,288 @@ async def create_async( :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. - :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting - :returns: The created TollfreeVerificationInstance + :returns: The updated TollfreeVerificationInstance + """ + payload, _, _ = await self._update_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance and return response metadata + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.TollfreeVerificationContext {}>".format(context) + + +class TollfreeVerificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: + """ + Build an instance of TollfreeVerificationInstance + + :param payload: Payload response from the API + """ + + return TollfreeVerificationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.TollfreeVerificationPage>" + + +class TollfreeVerificationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TollfreeVerificationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Tollfree/Verifications" + + def _create( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -864,6 +1854,20 @@ async def create_async( "BusinessContactEmail": business_contact_email, "BusinessContactPhone": business_contact_phone, "ExternalReferenceId": external_reference_id, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -872,11 +1876,635 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created TollfreeVerificationInstance + """ + payload, _, _ = self._create( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance(self._version, payload) + + def create_with_http_info( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TollfreeVerificationInstance and return response metadata + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "CustomerProfileSid": customer_profile_sid, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ExternalReferenceId": external_reference_id, + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "BusinessRegistrationPhoneNumber": business_registration_phone_number, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Asynchronously create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created TollfreeVerificationInstance + """ + payload, _, _ = await self._create_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TollfreeVerificationInstance and return response metadata + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) - - return TollfreeVerificationInstance(self._version, payload) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -884,6 +2512,7 @@ def stream( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[TollfreeVerificationInstance]: @@ -897,6 +2526,7 @@ def stream( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -912,6 +2542,7 @@ def stream( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, page_size=limits["page_size"], ) @@ -923,6 +2554,7 @@ async def stream_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[TollfreeVerificationInstance]: @@ -936,6 +2568,7 @@ async def stream_async( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -951,17 +2584,101 @@ async def stream_async( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, page_size=limits["page_size"], ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, tollfree_phone_number_sid: Union[str, object] = values.unset, status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TollfreeVerificationInstance]: @@ -974,6 +2691,7 @@ def list( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -983,12 +2701,14 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( tollfree_phone_number_sid=tollfree_phone_number_sid, status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, limit=limit, page_size=page_size, ) @@ -1000,6 +2720,7 @@ async def list_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TollfreeVerificationInstance]: @@ -1012,6 +2733,7 @@ async def list_async( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -1021,6 +2743,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1028,17 +2751,99 @@ async def list_async( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, tollfree_phone_number_sid: Union[str, object] = values.unset, status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1051,6 +2856,7 @@ def page( :param status: The compliance status of the Tollfree Verification record. :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1063,6 +2869,7 @@ def page( "Status": status, "ExternalReferenceId": external_reference_id, "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -1084,6 +2891,7 @@ async def page_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1096,6 +2904,7 @@ async def page_async( :param status: The compliance status of the Tollfree Verification record. :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1108,6 +2917,7 @@ async def page_async( "Status": status, "ExternalReferenceId": external_reference_id, "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -1123,6 +2933,106 @@ async def page_async( ) return TollfreeVerificationPage(self._version, response) + def page_with_http_info( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollfreeVerificationPage, status code, and headers + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TollfreeVerificationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TollfreeVerificationPage, status code, and headers + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TollfreeVerificationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TollfreeVerificationPage: """ Retrieve a specific page of TollfreeVerificationInstance records from the API. diff --git a/twilio/rest/messaging/v1/usecase.py b/twilio/rest/messaging/v1/usecase.py index fe811e0c84..46e9bf390f 100644 --- a/twilio/rest/messaging/v1/usecase.py +++ b/twilio/rest/messaging/v1/usecase.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,38 +54,78 @@ def __init__(self, version: Version): self._uri = "/Services/Usecases" - def fetch(self) -> UsecaseInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the UsecaseInstance + Internal helper for fetch operation - - :returns: The fetched UsecaseInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> UsecaseInstance: + """ + Fetch the UsecaseInstance + + :returns: The fetched UsecaseInstance + """ + payload, _, _ = self._fetch() return UsecaseInstance(self._version, payload) - async def fetch_async(self) -> UsecaseInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the UsecaseInstance + Fetch the UsecaseInstance and return response metadata - :returns: The fetched UsecaseInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UsecaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + payload, _, _ = await self._fetch_async() return UsecaseInstance(self._version, payload) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the UsecaseInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = UsecaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v2/__init__.py b/twilio/rest/messaging/v2/__init__.py new file mode 100644 index 0000000000..8dd64eba5c --- /dev/null +++ b/twilio/rest/messaging/v2/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v2.channels_sender import ChannelsSenderList +from twilio.rest.messaging.v2.domain_certs import DomainCertsList +from twilio.rest.messaging.v2.typing_indicator import TypingIndicatorList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v2") + self._channels_senders: Optional[ChannelsSenderList] = None + self._domain_certs: Optional[DomainCertsList] = None + self._typing_indicator: Optional[TypingIndicatorList] = None + + @property + def channels_senders(self) -> ChannelsSenderList: + if self._channels_senders is None: + self._channels_senders = ChannelsSenderList(self) + return self._channels_senders + + @property + def domain_certs(self) -> DomainCertsList: + if self._domain_certs is None: + self._domain_certs = DomainCertsList(self) + return self._domain_certs + + @property + def typing_indicator(self) -> TypingIndicatorList: + if self._typing_indicator is None: + self._typing_indicator = TypingIndicatorList(self) + return self._typing_indicator + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2>" diff --git a/twilio/rest/messaging/v2/channels_sender.py b/twilio/rest/messaging/v2/channels_sender.py new file mode 100644 index 0000000000..603a4c7ed8 --- /dev/null +++ b/twilio/rest/messaging/v2/channels_sender.py @@ -0,0 +1,2005 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelsSenderInstance(InstanceResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + class MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + class Status(object): + CREATING = "CREATING" + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + VERIFYING = "VERIFYING" + ONLINE_UPDATING = "ONLINE:UPDATING" + TWILIO_REVIEW = "TWILIO_REVIEW" + DRAFT = "DRAFT" + STUBBED = "STUBBED" + + class MessagingV2RcsCarrierStatus(object): + UNKNOWN = "UNKNOWN" + UNLAUNCHED = "UNLAUNCHED" + CARRIER_REVIEW = "CARRIER_REVIEW" + APPROVED = "APPROVED" + REJECTED = "REJECTED" + SUSPENDED = "SUSPENDED" + + class MessagingV2RcsCountryStatus(object): + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + TWILIO_REVIEW = "TWILIO_REVIEW" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + + """ + :ivar sid: The SID of the sender. + :ivar status: + :ivar sender_id: The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + :ivar properties: + :ivar offline_reasons: The reasons why the sender is offline. + :ivar compliance: + :ivar url: The URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["ChannelsSenderInstance.Status"] = payload.get("status") + self.sender_id: Optional[str] = payload.get("sender_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[str] = payload.get("configuration") + self.webhook: Optional[str] = payload.get("webhook") + self.profile: Optional[str] = payload.get("profile") + self.properties: Optional[str] = payload.get("properties") + self.offline_reasons: Optional[List[str]] = payload.get("offline_reasons") + self.compliance: Optional[str] = payload.get("compliance") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ChannelsSenderContext] = None + + @property + def _proxy(self) -> "ChannelsSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelsSenderContext for this ChannelsSenderInstance + """ + if self._context is None: + self._context = ChannelsSenderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "ChannelsSenderInstance": + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return self._proxy.update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return await self._proxy.update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + def update_with_http_info( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelsSenderInstance with HTTP info + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + async def update_with_http_info_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelsSenderInstance with HTTP info + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.ChannelsSenderInstance {}>".format(context) + + +class ChannelsSenderContext(InstanceContext): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + class MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelsSenderContext + + :param version: Version that contains the resource + :param sid: The SID of the sender. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/Senders/{sid}".format(**self._solution) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelsSenderInstance: + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + payload, _, _ = self._fetch() + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + payload, _, _ = await self._fetch_async() + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + payload, _, _ = self._update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + instance = ChannelsSenderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + payload, _, _ = await self._update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_update: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update + ) + instance = ChannelsSenderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.ChannelsSenderContext {}>".format(context) + + +class ChannelsSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelsSenderInstance: + """ + Build an instance of ChannelsSenderInstance + + :param payload: Payload response from the API + """ + + return ChannelsSenderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.ChannelsSenderPage>" + + +class ChannelsSenderList(ListResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account (WABA) to use for this sender. + :ivar verification_method: The verification method. + :ivar verification_code: The verification code. + :ivar voice_application_sid: The SID of the Twilio Voice application. + :ivar account_type: The account type for ISV Account Type Migration. Set to 'ISV' or 'ISVSubAccount' to configure, empty string to clear, or omit to preserve the existing value. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + self.account_type: Optional["ChannelsSenderInstance.str"] = payload.get( + "account_type" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + "account_type": self.account_type, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. Required for WhatsApp senders and must follow [Meta's display name guidelines](https://www.facebook.com/business/help/757569725593362). + :ivar about: The profile about text for the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar banner_url: The banner URL of the sender. + :ivar privacy_url: The privacy URL of the sender. Must be a publicly accessible HTTP or HTTPS URI associated with the sender. + :ivar terms_of_service_url: The terms of service URL of the sender. + :ivar accent_color: The color theme of the sender. Must be in hex format and have at least a 4:5:1 contrast ratio against white. + :ivar use_case: The messaging use case type for the RCS sender. Allowed values are `PROMOTIONAL`, `TRANSACTIONAL`, `OTP`, `MULTI_USE`. Defaults to `MULTI_USE` if not provided. Cannot be modified after launch. + :ivar vertical: The vertical of the sender. Allowed values are: - `Alcohol` - `Automotive` - `Beauty, Spa and Salon` - `Clothing and Apparel` - `Education` - `Entertainment` - `Event Planning and Service` - `Finance and Banking` - `Food and Grocery` - `Hotel and Lodging` - `Matrimony Service` - `Medical and Health` - `Non-profit` - `Online Gambling` - `OTC Drugs` - `Other` - `Physical Gambling` - `Professional Services` - `Public Service` - `Restaurant` - `Shopping and Retail` - `Travel and Transportation` + :ivar websites: The websites of the sender. + :ivar emails: The emails of the sender. + :ivar phone_numbers: The phone numbers of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.logo_url: Optional[str] = payload.get("logo_url") + self.banner_url: Optional[str] = payload.get("banner_url") + self.privacy_url: Optional[str] = payload.get("privacy_url") + self.terms_of_service_url: Optional[str] = payload.get( + "terms_of_service_url" + ) + self.accent_color: Optional[str] = payload.get("accent_color") + self.use_case: Optional["ChannelsSenderInstance.str"] = payload.get( + "use_case" + ) + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.phone_numbers: Optional[Dict[str, object]] = payload.get( + "phone_numbers" + ) + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "logo_url": self.logo_url, + "banner_url": self.banner_url, + "privacy_url": self.privacy_url, + "terms_of_service_url": self.terms_of_service_url, + "accent_color": self.accent_color, + "use_case": self.use_case, + "vertical": self.vertical, + "websites": self.websites, + "emails": self.emails, + "phone_numbers": self.phone_numbers, + } + + class MessagingV2ChannelsSenderProfileGenericResponseEmails(object): + """ + :ivar email: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.email: Optional[str] = payload.get("email") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "email": self.email, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponsePhoneNumbers(object): + """ + :ivar phone_number: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "label": self.label, + } + + class MessagingV2ChannelsSenderProfileGenericResponseWebsites(object): + """ + :ivar website: + :ivar label: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.website: Optional[str] = payload.get("website") + self.label: Optional[str] = payload.get("label") + + def to_dict(self): + return { + "website": self.website, + "label": self.label, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of the sender in `whatsapp:<E.164_PHONE_NUMBER>` format. + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar friendly_name: Optional display label for the sender in the Twilio Console. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method for the webhook. + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method for the fallback webhook. + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + class MessagingV2RcsCarrier(object): + """ + :ivar name: The name of the carrier. For example, `Verizon` or `AT&T` for US. + :ivar status: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.status: Optional[MessagingV2RcsCarrierStatus] = payload.get("status") + + def to_dict(self): + return { + "name": self.name, + "status": self.status.to_dict() if self.status is not None else None, + } + + class MessagingV2RcsComplianceCountryResponse(object): + """ + :ivar country: The ISO 3166-1 alpha-2 country code. + :ivar registration_sid: The default compliance registration SID (e.g., from CR-Google) that applies to all countries unless overridden in the `countries` array. + :ivar status: + :ivar carriers: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.country: Optional[str] = payload.get("country") + self.registration_sid: Optional[str] = payload.get("registration_sid") + self.status: Optional[MessagingV2RcsCountryStatus] = payload.get("status") + self.carriers: Optional[List[MessagingV2RcsCarrier]] = payload.get( + "carriers" + ) + + def to_dict(self): + return { + "country": self.country, + "registration_sid": self.registration_sid, + "status": self.status.to_dict() if self.status is not None else None, + "carriers": ( + [carriers.to_dict() for carriers in self.carriers] + if self.carriers is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the ChannelsSenderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Channels/Senders" + + def _create( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + payload, _, _ = self._create( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + return ChannelsSenderInstance(self._version, payload) + + def create_with_http_info( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ApiResponse: + """ + Create the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + instance = ChannelsSenderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Asynchronously create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + payload, _, _ = await self._create_async( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + return ChannelsSenderInstance(self._version, payload) + + async def create_with_http_info_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ApiResponse: + """ + Asynchronously create the ChannelsSenderInstance and return response metadata + + :param messaging_v2_channels_sender_requests_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + messaging_v2_channels_sender_requests_create=messaging_v2_channels_sender_requests_create + ) + instance = ChannelsSenderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelsSenderInstance]: + """ + Streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(channel=channel, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelsSenderInstance]: + """ + Asynchronously streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(channel=channel, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelsSenderInstance and returns headers from first page + + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel=channel, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelsSenderInstance and returns headers from first page + + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel=channel, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + channel=channel, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Asynchronously lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + channel=channel, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelsSenderInstance and returns headers from first page + + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel=channel, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelsSenderInstance and returns headers from first page + + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel=channel, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + async def page_async( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Asynchronously retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + def page_with_http_info( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelsSenderPage, status code, and headers + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChannelsSenderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChannelsSenderPage, status code, and headers + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChannelsSenderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ChannelsSenderPage: + """ + Retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelsSenderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ChannelsSenderPage: + """ + Asynchronously retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelsSenderPage(self._version, response) + + def get(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: The SID of the sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: The SID of the sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.ChannelsSenderList>" diff --git a/twilio/rest/messaging/v2/domain_certs.py b/twilio/rest/messaging/v2/domain_certs.py new file mode 100644 index 0000000000..84c0f5b58c --- /dev/null +++ b/twilio/rest/messaging/v2/domain_certs.py @@ -0,0 +1,285 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainCertsInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar date_updated: Date that this Domain was last updated. + :ivar date_expires: Date that the private certificate associated with this domain expires. You will need to update the certificate before that date to ensure your shortened links will continue to work. + :ivar date_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar managed: Boolean field that indicates whether the certificate is managed by Twilio or uploaded by the customer. + :ivar requesting: Boolean field that indicates whether a Twilio managed cert request is in progress or completed. True indicates a request is in progress and false indicates the request has completed or not requested yet. + :ivar url: + :ivar cert_in_validation: Optional JSON field describing the status and upload date of a new certificate in the process of validation + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.managed: Optional[bool] = payload.get("managed") + self.requesting: Optional[bool] = payload.get("requesting") + self.url: Optional[str] = payload.get("url") + self.cert_in_validation: Optional[Dict[str, object]] = payload.get( + "cert_in_validation" + ) + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + + self._context: Optional[DomainCertsContext] = None + + @property + def _proxy(self) -> "DomainCertsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainCertsContext for this DomainCertsInstance + """ + if self._context is None: + self._context = DomainCertsContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def fetch(self) -> "DomainCertsInstance": + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainCertsInstance": + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.DomainCertsInstance {}>".format(context) + + +class DomainCertsContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainCertsContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/Certificate".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = self._fetch() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + payload, _, _ = await self._fetch_async() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.DomainCertsContext {}>".format(context) + + +class DomainCertsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainCertsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.DomainCertsList>" diff --git a/twilio/rest/messaging/v2/typing_indicator.py b/twilio/rest/messaging/v2/typing_indicator.py new file mode 100644 index 0000000000..e27ebdfb2c --- /dev/null +++ b/twilio/rest/messaging/v2/typing_indicator.py @@ -0,0 +1,169 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TypingIndicatorInstance(InstanceResource): + """ + :ivar success: Indicates if the typing indicator was sent successfully. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.success: Optional[bool] = payload.get("success") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V2.TypingIndicatorInstance>" + + +class TypingIndicatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TypingIndicatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Indicators/Typing.json" + + def _create(self, channel: str, message_id: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "channel": channel, + "messageId": message_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self, channel: str, message_id: str) -> TypingIndicatorInstance: + """ + Create the TypingIndicatorInstance + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = self._create(channel=channel, message_id=message_id) + return TypingIndicatorInstance(self._version, payload) + + def create_with_http_info(self, channel: str, message_id: str) -> ApiResponse: + """ + Create the TypingIndicatorInstance and return response metadata + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel=channel, message_id=message_id + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, channel: str, message_id: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "channel": channel, + "messageId": message_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, channel: str, message_id: str + ) -> TypingIndicatorInstance: + """ + Asynchronously create the TypingIndicatorInstance + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = await self._create_async(channel=channel, message_id=message_id) + return TypingIndicatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, channel: str, message_id: str + ) -> ApiResponse: + """ + Asynchronously create the TypingIndicatorInstance and return response metadata + + :param channel: Shared channel identifier + :param message_id: Message SID that identifies the conversation thread for the typing indicator. Must be a valid Twilio Message SID (SM*) or Media SID (MM*) from an existing WhatsApp conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel=channel, message_id=message_id + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.TypingIndicatorList>" diff --git a/twilio/rest/messaging/v3/__init__.py b/twilio/rest/messaging/v3/__init__.py new file mode 100644 index 0000000000..20229f1936 --- /dev/null +++ b/twilio/rest/messaging/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v3.typing_indicator import TypingIndicatorList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v3") + self._typing_indicator: Optional[TypingIndicatorList] = None + + @property + def typing_indicator(self) -> TypingIndicatorList: + if self._typing_indicator is None: + self._typing_indicator = TypingIndicatorList(self) + return self._typing_indicator + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V3>" diff --git a/twilio/rest/messaging/v3/typing_indicator.py b/twilio/rest/messaging/v3/typing_indicator.py new file mode 100644 index 0000000000..43f1732c60 --- /dev/null +++ b/twilio/rest/messaging/v3/typing_indicator.py @@ -0,0 +1,220 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TypingIndicatorInstance(InstanceResource): + + class TypingIndicatorRequest(object): + """ + :ivar channel: The messaging channel. Must be \"RCS\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The RCS agent identifier of the sender (business). + :ivar to: The RCS recipient identifier in E.164 format prefixed with \"rcs:\". + :ivar event: The type of typing event. Currently only \"START\" is supported for RCS, indicating the agent began typing. Defaults to \"START\". + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["TypingIndicatorInstance.str"] = payload.get( + "channel" + ) + self.message_id: Optional[str] = payload.get("messageId") + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.event: Optional["TypingIndicatorInstance.str"] = payload.get("event") + + def to_dict(self): + return { + "channel": self.channel, + "messageId": self.message_id, + "from": self._from, + "to": self.to, + "event": self.event, + } + + """ + :ivar success: Indicates if the typing indicator was sent successfully. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.success: Optional[bool] = payload.get("success") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V3.TypingIndicatorInstance>" + + +class TypingIndicatorList(ListResource): + + class TypingIndicatorRequest(object): + """ + :ivar channel: The messaging channel. Must be \"RCS\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The RCS agent identifier of the sender (business). + :ivar to: The RCS recipient identifier in E.164 format prefixed with \"rcs:\". + :ivar event: The type of typing event. Currently only \"START\" is supported for RCS, indicating the agent began typing. Defaults to \"START\". + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["TypingIndicatorInstance.str"] = payload.get( + "channel" + ) + self.message_id: Optional[str] = payload.get("messageId") + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.event: Optional["TypingIndicatorInstance.str"] = payload.get("event") + + def to_dict(self): + return { + "channel": self.channel, + "messageId": self.message_id, + "from": self._from, + "to": self.to, + "event": self.event, + } + + def __init__(self, version: Version): + """ + Initialize the TypingIndicatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Indicators/Typing.json" + + def _create(self, typing_indicator_request: TypingIndicatorRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = typing_indicator_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, typing_indicator_request: TypingIndicatorRequest + ) -> TypingIndicatorInstance: + """ + Create the TypingIndicatorInstance + + :param typing_indicator_request: + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = self._create(typing_indicator_request=typing_indicator_request) + return TypingIndicatorInstance(self._version, payload) + + def create_with_http_info( + self, typing_indicator_request: TypingIndicatorRequest + ) -> ApiResponse: + """ + Create the TypingIndicatorInstance and return response metadata + + :param typing_indicator_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + typing_indicator_request=typing_indicator_request + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = typing_indicator_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> TypingIndicatorInstance: + """ + Asynchronously create the TypingIndicatorInstance + + :param typing_indicator_request: + + :returns: The created TypingIndicatorInstance + """ + payload, _, _ = await self._create_async( + typing_indicator_request=typing_indicator_request + ) + return TypingIndicatorInstance(self._version, payload) + + async def create_with_http_info_async( + self, typing_indicator_request: TypingIndicatorRequest + ) -> ApiResponse: + """ + Asynchronously create the TypingIndicatorInstance and return response metadata + + :param typing_indicator_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + typing_indicator_request=typing_indicator_request + ) + instance = TypingIndicatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V3.TypingIndicatorList>" diff --git a/twilio/rest/microvisor/__init__.py b/twilio/rest/microvisor/__init__.py deleted file mode 100644 index 6bf448b29c..0000000000 --- a/twilio/rest/microvisor/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -from warnings import warn - -from twilio.rest.microvisor.MicrovisorBase import MicrovisorBase -from twilio.rest.microvisor.v1.account_config import AccountConfigList -from twilio.rest.microvisor.v1.account_secret import AccountSecretList -from twilio.rest.microvisor.v1.app import AppList -from twilio.rest.microvisor.v1.device import DeviceList - - -class Microvisor(MicrovisorBase): - @property - def account_configs(self) -> AccountConfigList: - warn( - "account_configs is deprecated. Use v1.account_configs instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.account_configs - - @property - def account_secrets(self) -> AccountSecretList: - warn( - "account_secrets is deprecated. Use v1.account_secrets instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.account_secrets - - @property - def apps(self) -> AppList: - warn( - "apps is deprecated. Use v1.apps instead.", DeprecationWarning, stacklevel=2 - ) - return self.v1.apps - - @property - def devices(self) -> DeviceList: - warn( - "devices is deprecated. Use v1.devices instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.devices diff --git a/twilio/rest/microvisor/v1/__init__.py b/twilio/rest/microvisor/v1/__init__.py deleted file mode 100644 index 22010d62e5..0000000000 --- a/twilio/rest/microvisor/v1/__init__.py +++ /dev/null @@ -1,67 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Optional -from twilio.base.version import Version -from twilio.base.domain import Domain -from twilio.rest.microvisor.v1.account_config import AccountConfigList -from twilio.rest.microvisor.v1.account_secret import AccountSecretList -from twilio.rest.microvisor.v1.app import AppList -from twilio.rest.microvisor.v1.device import DeviceList - - -class V1(Version): - - def __init__(self, domain: Domain): - """ - Initialize the V1 version of Microvisor - - :param domain: The Twilio.microvisor domain - """ - super().__init__(domain, "v1") - self._account_configs: Optional[AccountConfigList] = None - self._account_secrets: Optional[AccountSecretList] = None - self._apps: Optional[AppList] = None - self._devices: Optional[DeviceList] = None - - @property - def account_configs(self) -> AccountConfigList: - if self._account_configs is None: - self._account_configs = AccountConfigList(self) - return self._account_configs - - @property - def account_secrets(self) -> AccountSecretList: - if self._account_secrets is None: - self._account_secrets = AccountSecretList(self) - return self._account_secrets - - @property - def apps(self) -> AppList: - if self._apps is None: - self._apps = AppList(self) - return self._apps - - @property - def devices(self) -> DeviceList: - if self._devices is None: - self._devices = DeviceList(self) - return self._devices - - def __repr__(self) -> str: - """ - Provide a friendly representation - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1>" diff --git a/twilio/rest/microvisor/v1/account_config.py b/twilio/rest/microvisor/v1/account_config.py deleted file mode 100644 index 7faba8acb1..0000000000 --- a/twilio/rest/microvisor/v1/account_config.py +++ /dev/null @@ -1,585 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class AccountConfigInstance(InstanceResource): - """ - :ivar key: The config key; up to 100 characters. - :ivar date_updated: - :ivar value: The config value; up to 4096 characters. - :ivar url: The absolute URL of the Config. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], key: Optional[str] = None - ): - super().__init__(version) - - self.key: Optional[str] = payload.get("key") - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.value: Optional[str] = payload.get("value") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "key": key or self.key, - } - self._context: Optional[AccountConfigContext] = None - - @property - def _proxy(self) -> "AccountConfigContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AccountConfigContext for this AccountConfigInstance - """ - if self._context is None: - self._context = AccountConfigContext( - self._version, - key=self._solution["key"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the AccountConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "AccountConfigInstance": - """ - Fetch the AccountConfigInstance - - - :returns: The fetched AccountConfigInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AccountConfigInstance": - """ - Asynchronous coroutine to fetch the AccountConfigInstance - - - :returns: The fetched AccountConfigInstance - """ - return await self._proxy.fetch_async() - - def update(self, value: str) -> "AccountConfigInstance": - """ - Update the AccountConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated AccountConfigInstance - """ - return self._proxy.update( - value=value, - ) - - async def update_async(self, value: str) -> "AccountConfigInstance": - """ - Asynchronous coroutine to update the AccountConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated AccountConfigInstance - """ - return await self._proxy.update_async( - value=value, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AccountConfigInstance {}>".format(context) - - -class AccountConfigContext(InstanceContext): - - def __init__(self, version: Version, key: str): - """ - Initialize the AccountConfigContext - - :param version: Version that contains the resource - :param key: The config key; up to 100 characters. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "key": key, - } - self._uri = "/Configs/{key}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the AccountConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> AccountConfigInstance: - """ - Fetch the AccountConfigInstance - - - :returns: The fetched AccountConfigInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return AccountConfigInstance( - self._version, - payload, - key=self._solution["key"], - ) - - async def fetch_async(self) -> AccountConfigInstance: - """ - Asynchronous coroutine to fetch the AccountConfigInstance - - - :returns: The fetched AccountConfigInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return AccountConfigInstance( - self._version, - payload, - key=self._solution["key"], - ) - - def update(self, value: str) -> AccountConfigInstance: - """ - Update the AccountConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated AccountConfigInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload, key=self._solution["key"]) - - async def update_async(self, value: str) -> AccountConfigInstance: - """ - Asynchronous coroutine to update the AccountConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated AccountConfigInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload, key=self._solution["key"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AccountConfigContext {}>".format(context) - - -class AccountConfigPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AccountConfigInstance: - """ - Build an instance of AccountConfigInstance - - :param payload: Payload response from the API - """ - return AccountConfigInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AccountConfigPage>" - - -class AccountConfigList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the AccountConfigList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Configs" - - def create(self, key: str, value: str) -> AccountConfigInstance: - """ - Create the AccountConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created AccountConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload) - - async def create_async(self, key: str, value: str) -> AccountConfigInstance: - """ - Asynchronously create the AccountConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created AccountConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AccountConfigInstance]: - """ - Streams AccountConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AccountConfigInstance]: - """ - Asynchronously streams AccountConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountConfigInstance]: - """ - Lists AccountConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountConfigInstance]: - """ - Asynchronously lists AccountConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountConfigPage: - """ - Retrieve a single page of AccountConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AccountConfigPage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountConfigPage: - """ - Asynchronously retrieve a single page of AccountConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AccountConfigPage(self._version, response) - - def get_page(self, target_url: str) -> AccountConfigPage: - """ - Retrieve a specific page of AccountConfigInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AccountConfigInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AccountConfigPage(self._version, response) - - async def get_page_async(self, target_url: str) -> AccountConfigPage: - """ - Asynchronously retrieve a specific page of AccountConfigInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AccountConfigInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AccountConfigPage(self._version, response) - - def get(self, key: str) -> AccountConfigContext: - """ - Constructs a AccountConfigContext - - :param key: The config key; up to 100 characters. - """ - return AccountConfigContext(self._version, key=key) - - def __call__(self, key: str) -> AccountConfigContext: - """ - Constructs a AccountConfigContext - - :param key: The config key; up to 100 characters. - """ - return AccountConfigContext(self._version, key=key) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AccountConfigList>" diff --git a/twilio/rest/microvisor/v1/account_secret.py b/twilio/rest/microvisor/v1/account_secret.py deleted file mode 100644 index 13ca961e61..0000000000 --- a/twilio/rest/microvisor/v1/account_secret.py +++ /dev/null @@ -1,583 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class AccountSecretInstance(InstanceResource): - """ - :ivar key: The secret key; up to 100 characters. - :ivar date_rotated: - :ivar url: The absolute URL of the Secret. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], key: Optional[str] = None - ): - super().__init__(version) - - self.key: Optional[str] = payload.get("key") - self.date_rotated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_rotated") - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "key": key or self.key, - } - self._context: Optional[AccountSecretContext] = None - - @property - def _proxy(self) -> "AccountSecretContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AccountSecretContext for this AccountSecretInstance - """ - if self._context is None: - self._context = AccountSecretContext( - self._version, - key=self._solution["key"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the AccountSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "AccountSecretInstance": - """ - Fetch the AccountSecretInstance - - - :returns: The fetched AccountSecretInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AccountSecretInstance": - """ - Asynchronous coroutine to fetch the AccountSecretInstance - - - :returns: The fetched AccountSecretInstance - """ - return await self._proxy.fetch_async() - - def update(self, value: str) -> "AccountSecretInstance": - """ - Update the AccountSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated AccountSecretInstance - """ - return self._proxy.update( - value=value, - ) - - async def update_async(self, value: str) -> "AccountSecretInstance": - """ - Asynchronous coroutine to update the AccountSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated AccountSecretInstance - """ - return await self._proxy.update_async( - value=value, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AccountSecretInstance {}>".format(context) - - -class AccountSecretContext(InstanceContext): - - def __init__(self, version: Version, key: str): - """ - Initialize the AccountSecretContext - - :param version: Version that contains the resource - :param key: The secret key; up to 100 characters. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "key": key, - } - self._uri = "/Secrets/{key}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the AccountSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> AccountSecretInstance: - """ - Fetch the AccountSecretInstance - - - :returns: The fetched AccountSecretInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return AccountSecretInstance( - self._version, - payload, - key=self._solution["key"], - ) - - async def fetch_async(self) -> AccountSecretInstance: - """ - Asynchronous coroutine to fetch the AccountSecretInstance - - - :returns: The fetched AccountSecretInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return AccountSecretInstance( - self._version, - payload, - key=self._solution["key"], - ) - - def update(self, value: str) -> AccountSecretInstance: - """ - Update the AccountSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated AccountSecretInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload, key=self._solution["key"]) - - async def update_async(self, value: str) -> AccountSecretInstance: - """ - Asynchronous coroutine to update the AccountSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated AccountSecretInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload, key=self._solution["key"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AccountSecretContext {}>".format(context) - - -class AccountSecretPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AccountSecretInstance: - """ - Build an instance of AccountSecretInstance - - :param payload: Payload response from the API - """ - return AccountSecretInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AccountSecretPage>" - - -class AccountSecretList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the AccountSecretList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Secrets" - - def create(self, key: str, value: str) -> AccountSecretInstance: - """ - Create the AccountSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created AccountSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload) - - async def create_async(self, key: str, value: str) -> AccountSecretInstance: - """ - Asynchronously create the AccountSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created AccountSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AccountSecretInstance]: - """ - Streams AccountSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AccountSecretInstance]: - """ - Asynchronously streams AccountSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountSecretInstance]: - """ - Lists AccountSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountSecretInstance]: - """ - Asynchronously lists AccountSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountSecretPage: - """ - Retrieve a single page of AccountSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AccountSecretPage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountSecretPage: - """ - Asynchronously retrieve a single page of AccountSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AccountSecretPage(self._version, response) - - def get_page(self, target_url: str) -> AccountSecretPage: - """ - Retrieve a specific page of AccountSecretInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AccountSecretInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AccountSecretPage(self._version, response) - - async def get_page_async(self, target_url: str) -> AccountSecretPage: - """ - Asynchronously retrieve a specific page of AccountSecretInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AccountSecretInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AccountSecretPage(self._version, response) - - def get(self, key: str) -> AccountSecretContext: - """ - Constructs a AccountSecretContext - - :param key: The secret key; up to 100 characters. - """ - return AccountSecretContext(self._version, key=key) - - def __call__(self, key: str) -> AccountSecretContext: - """ - Constructs a AccountSecretContext - - :param key: The secret key; up to 100 characters. - """ - return AccountSecretContext(self._version, key=key) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AccountSecretList>" diff --git a/twilio/rest/microvisor/v1/app/__init__.py b/twilio/rest/microvisor/v1/app/__init__.py deleted file mode 100644 index 8cfbbe68df..0000000000 --- a/twilio/rest/microvisor/v1/app/__init__.py +++ /dev/null @@ -1,485 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.microvisor.v1.app.app_manifest import AppManifestList - - -class AppInstance(InstanceResource): - """ - :ivar sid: A 34-character string that uniquely identifies this App. - :ivar account_sid: The unique SID identifier of the Account. - :ivar hash: App manifest hash represented as `hash_algorithm:hash_value`. - :ivar unique_name: A developer-defined string that uniquely identifies the App. This value must be unique for all Apps on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource. - :ivar date_created: The date that this App was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date that this App was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar url: The URL of this resource. - :ivar links: - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.hash: Optional[str] = payload.get("hash") - self.unique_name: Optional[str] = payload.get("unique_name") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[AppContext] = None - - @property - def _proxy(self) -> "AppContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AppContext for this AppInstance - """ - if self._context is None: - self._context = AppContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the AppInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AppInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "AppInstance": - """ - Fetch the AppInstance - - - :returns: The fetched AppInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AppInstance": - """ - Asynchronous coroutine to fetch the AppInstance - - - :returns: The fetched AppInstance - """ - return await self._proxy.fetch_async() - - @property - def app_manifests(self) -> AppManifestList: - """ - Access the app_manifests - """ - return self._proxy.app_manifests - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AppInstance {}>".format(context) - - -class AppContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the AppContext - - :param version: Version that contains the resource - :param sid: A 34-character string that uniquely identifies this App. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Apps/{sid}".format(**self._solution) - - self._app_manifests: Optional[AppManifestList] = None - - def delete(self) -> bool: - """ - Deletes the AppInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AppInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> AppInstance: - """ - Fetch the AppInstance - - - :returns: The fetched AppInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return AppInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> AppInstance: - """ - Asynchronous coroutine to fetch the AppInstance - - - :returns: The fetched AppInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return AppInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - @property - def app_manifests(self) -> AppManifestList: - """ - Access the app_manifests - """ - if self._app_manifests is None: - self._app_manifests = AppManifestList( - self._version, - self._solution["sid"], - ) - return self._app_manifests - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AppContext {}>".format(context) - - -class AppPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> AppInstance: - """ - Build an instance of AppInstance - - :param payload: Payload response from the API - """ - return AppInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AppPage>" - - -class AppList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the AppList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Apps" - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AppInstance]: - """ - Streams AppInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AppInstance]: - """ - Asynchronously streams AppInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AppInstance]: - """ - Lists AppInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AppInstance]: - """ - Asynchronously lists AppInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AppPage: - """ - Retrieve a single page of AppInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AppInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AppPage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AppPage: - """ - Asynchronously retrieve a single page of AppInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AppInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return AppPage(self._version, response) - - def get_page(self, target_url: str) -> AppPage: - """ - Retrieve a specific page of AppInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AppInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return AppPage(self._version, response) - - async def get_page_async(self, target_url: str) -> AppPage: - """ - Asynchronously retrieve a specific page of AppInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of AppInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return AppPage(self._version, response) - - def get(self, sid: str) -> AppContext: - """ - Constructs a AppContext - - :param sid: A 34-character string that uniquely identifies this App. - """ - return AppContext(self._version, sid=sid) - - def __call__(self, sid: str) -> AppContext: - """ - Constructs a AppContext - - :param sid: A 34-character string that uniquely identifies this App. - """ - return AppContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AppList>" diff --git a/twilio/rest/microvisor/v1/app/app_manifest.py b/twilio/rest/microvisor/v1/app/app_manifest.py deleted file mode 100644 index 0412cadcc1..0000000000 --- a/twilio/rest/microvisor/v1/app/app_manifest.py +++ /dev/null @@ -1,193 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, Optional -from twilio.base import values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version - - -class AppManifestInstance(InstanceResource): - """ - :ivar app_sid: A 34-character string that uniquely identifies this App. - :ivar hash: App manifest hash represented as `hash_algorithm:hash_value`. - :ivar encoded_bytes: The base-64 encoded manifest - :ivar url: The absolute URL of this Manifest. - """ - - def __init__(self, version: Version, payload: Dict[str, Any], app_sid: str): - super().__init__(version) - - self.app_sid: Optional[str] = payload.get("app_sid") - self.hash: Optional[str] = payload.get("hash") - self.encoded_bytes: Optional[str] = payload.get("encoded_bytes") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "app_sid": app_sid, - } - self._context: Optional[AppManifestContext] = None - - @property - def _proxy(self) -> "AppManifestContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AppManifestContext for this AppManifestInstance - """ - if self._context is None: - self._context = AppManifestContext( - self._version, - app_sid=self._solution["app_sid"], - ) - return self._context - - def fetch(self) -> "AppManifestInstance": - """ - Fetch the AppManifestInstance - - - :returns: The fetched AppManifestInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AppManifestInstance": - """ - Asynchronous coroutine to fetch the AppManifestInstance - - - :returns: The fetched AppManifestInstance - """ - return await self._proxy.fetch_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AppManifestInstance {}>".format(context) - - -class AppManifestContext(InstanceContext): - - def __init__(self, version: Version, app_sid: str): - """ - Initialize the AppManifestContext - - :param version: Version that contains the resource - :param app_sid: A 34-character string that uniquely identifies this App. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "app_sid": app_sid, - } - self._uri = "/Apps/{app_sid}/Manifest".format(**self._solution) - - def fetch(self) -> AppManifestInstance: - """ - Fetch the AppManifestInstance - - - :returns: The fetched AppManifestInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return AppManifestInstance( - self._version, - payload, - app_sid=self._solution["app_sid"], - ) - - async def fetch_async(self) -> AppManifestInstance: - """ - Asynchronous coroutine to fetch the AppManifestInstance - - - :returns: The fetched AppManifestInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return AppManifestInstance( - self._version, - payload, - app_sid=self._solution["app_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.AppManifestContext {}>".format(context) - - -class AppManifestList(ListResource): - - def __init__(self, version: Version, app_sid: str): - """ - Initialize the AppManifestList - - :param version: Version that contains the resource - :param app_sid: A 34-character string that uniquely identifies this App. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "app_sid": app_sid, - } - - def get(self) -> AppManifestContext: - """ - Constructs a AppManifestContext - - """ - return AppManifestContext(self._version, app_sid=self._solution["app_sid"]) - - def __call__(self) -> AppManifestContext: - """ - Constructs a AppManifestContext - - """ - return AppManifestContext(self._version, app_sid=self._solution["app_sid"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.AppManifestList>" diff --git a/twilio/rest/microvisor/v1/device/__init__.py b/twilio/rest/microvisor/v1/device/__init__.py deleted file mode 100644 index a3b3089162..0000000000 --- a/twilio/rest/microvisor/v1/device/__init__.py +++ /dev/null @@ -1,588 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.microvisor.v1.device.device_config import DeviceConfigList -from twilio.rest.microvisor.v1.device.device_secret import DeviceSecretList - - -class DeviceInstance(InstanceResource): - """ - :ivar sid: A 34-character string that uniquely identifies this Device. - :ivar unique_name: A developer-defined string that uniquely identifies the Device. This value must be unique for all Devices on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource. - :ivar account_sid: The unique SID identifier of the Account. - :ivar app: Information about the target App and the App reported by this Device. Contains the properties `target_sid`, `date_targeted`, `update_status` (one of `up-to-date`, `pending` and `error`), `update_error_code`, `reported_sid` and `date_reported`. - :ivar logging: Object specifying whether application logging is enabled for this Device. Contains the properties `enabled` and `date_expires`. - :ivar date_created: The date that this Device was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date that this Device was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar url: The URL of this resource. - :ivar links: The absolute URLs of related resources. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.app: Optional[Dict[str, object]] = payload.get("app") - self.logging: Optional[Dict[str, object]] = payload.get("logging") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[DeviceContext] = None - - @property - def _proxy(self) -> "DeviceContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeviceContext for this DeviceInstance - """ - if self._context is None: - self._context = DeviceContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "DeviceInstance": - """ - Fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DeviceInstance": - """ - Asynchronous coroutine to fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - return self._proxy.update( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - restart_app=restart_app, - ) - - async def update_async( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Asynchronous coroutine to update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - return await self._proxy.update_async( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - restart_app=restart_app, - ) - - @property - def device_configs(self) -> DeviceConfigList: - """ - Access the device_configs - """ - return self._proxy.device_configs - - @property - def device_secrets(self) -> DeviceSecretList: - """ - Access the device_secrets - """ - return self._proxy.device_secrets - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceInstance {}>".format(context) - - -class DeviceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the DeviceContext - - :param version: Version that contains the resource - :param sid: A 34-character string that uniquely identifies this Device. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Devices/{sid}".format(**self._solution) - - self._device_configs: Optional[DeviceConfigList] = None - self._device_secrets: Optional[DeviceSecretList] = None - - def fetch(self) -> DeviceInstance: - """ - Fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return DeviceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DeviceInstance: - """ - Asynchronous coroutine to fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return DeviceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": serialize.boolean_to_string(logging_enabled), - "RestartApp": serialize.boolean_to_string(restart_app), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Asynchronous coroutine to update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": serialize.boolean_to_string(logging_enabled), - "RestartApp": serialize.boolean_to_string(restart_app), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def device_configs(self) -> DeviceConfigList: - """ - Access the device_configs - """ - if self._device_configs is None: - self._device_configs = DeviceConfigList( - self._version, - self._solution["sid"], - ) - return self._device_configs - - @property - def device_secrets(self) -> DeviceSecretList: - """ - Access the device_secrets - """ - if self._device_secrets is None: - self._device_secrets = DeviceSecretList( - self._version, - self._solution["sid"], - ) - return self._device_secrets - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceContext {}>".format(context) - - -class DevicePage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> DeviceInstance: - """ - Build an instance of DeviceInstance - - :param payload: Payload response from the API - """ - return DeviceInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DevicePage>" - - -class DeviceList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the DeviceList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Devices" - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeviceInstance]: - """ - Streams DeviceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DeviceInstance]: - """ - Asynchronously streams DeviceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceInstance]: - """ - Lists DeviceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceInstance]: - """ - Asynchronously lists DeviceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DevicePage: - """ - Retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DevicePage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DevicePage: - """ - Asynchronously retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DevicePage(self._version, response) - - def get_page(self, target_url: str) -> DevicePage: - """ - Retrieve a specific page of DeviceInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DevicePage(self._version, response) - - async def get_page_async(self, target_url: str) -> DevicePage: - """ - Asynchronously retrieve a specific page of DeviceInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DevicePage(self._version, response) - - def get(self, sid: str) -> DeviceContext: - """ - Constructs a DeviceContext - - :param sid: A 34-character string that uniquely identifies this Device. - """ - return DeviceContext(self._version, sid=sid) - - def __call__(self, sid: str) -> DeviceContext: - """ - Constructs a DeviceContext - - :param sid: A 34-character string that uniquely identifies this Device. - """ - return DeviceContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DeviceList>" diff --git a/twilio/rest/microvisor/v1/device/device_config.py b/twilio/rest/microvisor/v1/device/device_config.py deleted file mode 100644 index b87063f53f..0000000000 --- a/twilio/rest/microvisor/v1/device/device_config.py +++ /dev/null @@ -1,622 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class DeviceConfigInstance(InstanceResource): - """ - :ivar device_sid: A 34-character string that uniquely identifies the parent Device. - :ivar key: The config key; up to 100 characters. - :ivar value: The config value; up to 4096 characters. - :ivar date_updated: - :ivar url: The absolute URL of the Config. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - device_sid: str, - key: Optional[str] = None, - ): - super().__init__(version) - - self.device_sid: Optional[str] = payload.get("device_sid") - self.key: Optional[str] = payload.get("key") - self.value: Optional[str] = payload.get("value") - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "device_sid": device_sid, - "key": key or self.key, - } - self._context: Optional[DeviceConfigContext] = None - - @property - def _proxy(self) -> "DeviceConfigContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeviceConfigContext for this DeviceConfigInstance - """ - if self._context is None: - self._context = DeviceConfigContext( - self._version, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DeviceConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DeviceConfigInstance": - """ - Fetch the DeviceConfigInstance - - - :returns: The fetched DeviceConfigInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DeviceConfigInstance": - """ - Asynchronous coroutine to fetch the DeviceConfigInstance - - - :returns: The fetched DeviceConfigInstance - """ - return await self._proxy.fetch_async() - - def update(self, value: str) -> "DeviceConfigInstance": - """ - Update the DeviceConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated DeviceConfigInstance - """ - return self._proxy.update( - value=value, - ) - - async def update_async(self, value: str) -> "DeviceConfigInstance": - """ - Asynchronous coroutine to update the DeviceConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated DeviceConfigInstance - """ - return await self._proxy.update_async( - value=value, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceConfigInstance {}>".format(context) - - -class DeviceConfigContext(InstanceContext): - - def __init__(self, version: Version, device_sid: str, key: str): - """ - Initialize the DeviceConfigContext - - :param version: Version that contains the resource - :param device_sid: A 34-character string that uniquely identifies the Device. - :param key: The config key; up to 100 characters. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "device_sid": device_sid, - "key": key, - } - self._uri = "/Devices/{device_sid}/Configs/{key}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the DeviceConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> DeviceConfigInstance: - """ - Fetch the DeviceConfigInstance - - - :returns: The fetched DeviceConfigInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return DeviceConfigInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - async def fetch_async(self) -> DeviceConfigInstance: - """ - Asynchronous coroutine to fetch the DeviceConfigInstance - - - :returns: The fetched DeviceConfigInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return DeviceConfigInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - def update(self, value: str) -> DeviceConfigInstance: - """ - Update the DeviceConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated DeviceConfigInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - async def update_async(self, value: str) -> DeviceConfigInstance: - """ - Asynchronous coroutine to update the DeviceConfigInstance - - :param value: The config value; up to 4096 characters. - - :returns: The updated DeviceConfigInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceConfigContext {}>".format(context) - - -class DeviceConfigPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> DeviceConfigInstance: - """ - Build an instance of DeviceConfigInstance - - :param payload: Payload response from the API - """ - return DeviceConfigInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DeviceConfigPage>" - - -class DeviceConfigList(ListResource): - - def __init__(self, version: Version, device_sid: str): - """ - Initialize the DeviceConfigList - - :param version: Version that contains the resource - :param device_sid: A 34-character string that uniquely identifies the Device. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "device_sid": device_sid, - } - self._uri = "/Devices/{device_sid}/Configs".format(**self._solution) - - def create(self, key: str, value: str) -> DeviceConfigInstance: - """ - Create the DeviceConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created DeviceConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - async def create_async(self, key: str, value: str) -> DeviceConfigInstance: - """ - Asynchronously create the DeviceConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created DeviceConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeviceConfigInstance]: - """ - Streams DeviceConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DeviceConfigInstance]: - """ - Asynchronously streams DeviceConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceConfigInstance]: - """ - Lists DeviceConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceConfigInstance]: - """ - Asynchronously lists DeviceConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceConfigPage: - """ - Retrieve a single page of DeviceConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DeviceConfigPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceConfigPage: - """ - Asynchronously retrieve a single page of DeviceConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DeviceConfigPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> DeviceConfigPage: - """ - Retrieve a specific page of DeviceConfigInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceConfigInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DeviceConfigPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> DeviceConfigPage: - """ - Asynchronously retrieve a specific page of DeviceConfigInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceConfigInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DeviceConfigPage(self._version, response, self._solution) - - def get(self, key: str) -> DeviceConfigContext: - """ - Constructs a DeviceConfigContext - - :param key: The config key; up to 100 characters. - """ - return DeviceConfigContext( - self._version, device_sid=self._solution["device_sid"], key=key - ) - - def __call__(self, key: str) -> DeviceConfigContext: - """ - Constructs a DeviceConfigContext - - :param key: The config key; up to 100 characters. - """ - return DeviceConfigContext( - self._version, device_sid=self._solution["device_sid"], key=key - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DeviceConfigList>" diff --git a/twilio/rest/microvisor/v1/device/device_secret.py b/twilio/rest/microvisor/v1/device/device_secret.py deleted file mode 100644 index 30b805ea6b..0000000000 --- a/twilio/rest/microvisor/v1/device/device_secret.py +++ /dev/null @@ -1,620 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class DeviceSecretInstance(InstanceResource): - """ - :ivar device_sid: A 34-character string that uniquely identifies the parent Device. - :ivar key: The secret key; up to 100 characters. - :ivar date_rotated: - :ivar url: The absolute URL of the Secret. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - device_sid: str, - key: Optional[str] = None, - ): - super().__init__(version) - - self.device_sid: Optional[str] = payload.get("device_sid") - self.key: Optional[str] = payload.get("key") - self.date_rotated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_rotated") - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "device_sid": device_sid, - "key": key or self.key, - } - self._context: Optional[DeviceSecretContext] = None - - @property - def _proxy(self) -> "DeviceSecretContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeviceSecretContext for this DeviceSecretInstance - """ - if self._context is None: - self._context = DeviceSecretContext( - self._version, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DeviceSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DeviceSecretInstance": - """ - Fetch the DeviceSecretInstance - - - :returns: The fetched DeviceSecretInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DeviceSecretInstance": - """ - Asynchronous coroutine to fetch the DeviceSecretInstance - - - :returns: The fetched DeviceSecretInstance - """ - return await self._proxy.fetch_async() - - def update(self, value: str) -> "DeviceSecretInstance": - """ - Update the DeviceSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated DeviceSecretInstance - """ - return self._proxy.update( - value=value, - ) - - async def update_async(self, value: str) -> "DeviceSecretInstance": - """ - Asynchronous coroutine to update the DeviceSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated DeviceSecretInstance - """ - return await self._proxy.update_async( - value=value, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceSecretInstance {}>".format(context) - - -class DeviceSecretContext(InstanceContext): - - def __init__(self, version: Version, device_sid: str, key: str): - """ - Initialize the DeviceSecretContext - - :param version: Version that contains the resource - :param device_sid: A 34-character string that uniquely identifies the Device. - :param key: The secret key; up to 100 characters. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "device_sid": device_sid, - "key": key, - } - self._uri = "/Devices/{device_sid}/Secrets/{key}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the DeviceSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> DeviceSecretInstance: - """ - Fetch the DeviceSecretInstance - - - :returns: The fetched DeviceSecretInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return DeviceSecretInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - async def fetch_async(self) -> DeviceSecretInstance: - """ - Asynchronous coroutine to fetch the DeviceSecretInstance - - - :returns: The fetched DeviceSecretInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return DeviceSecretInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - def update(self, value: str) -> DeviceSecretInstance: - """ - Update the DeviceSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated DeviceSecretInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - async def update_async(self, value: str) -> DeviceSecretInstance: - """ - Asynchronous coroutine to update the DeviceSecretInstance - - :param value: The secret value; up to 4096 characters. - - :returns: The updated DeviceSecretInstance - """ - - data = values.of( - { - "Value": value, - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, - payload, - device_sid=self._solution["device_sid"], - key=self._solution["key"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Microvisor.V1.DeviceSecretContext {}>".format(context) - - -class DeviceSecretPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> DeviceSecretInstance: - """ - Build an instance of DeviceSecretInstance - - :param payload: Payload response from the API - """ - return DeviceSecretInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DeviceSecretPage>" - - -class DeviceSecretList(ListResource): - - def __init__(self, version: Version, device_sid: str): - """ - Initialize the DeviceSecretList - - :param version: Version that contains the resource - :param device_sid: A 34-character string that uniquely identifies the Device. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "device_sid": device_sid, - } - self._uri = "/Devices/{device_sid}/Secrets".format(**self._solution) - - def create(self, key: str, value: str) -> DeviceSecretInstance: - """ - Create the DeviceSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created DeviceSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - async def create_async(self, key: str, value: str) -> DeviceSecretInstance: - """ - Asynchronously create the DeviceSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created DeviceSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeviceSecretInstance]: - """ - Streams DeviceSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DeviceSecretInstance]: - """ - Asynchronously streams DeviceSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceSecretInstance]: - """ - Lists DeviceSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceSecretInstance]: - """ - Asynchronously lists DeviceSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceSecretPage: - """ - Retrieve a single page of DeviceSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DeviceSecretPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceSecretPage: - """ - Asynchronously retrieve a single page of DeviceSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DeviceSecretPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> DeviceSecretPage: - """ - Retrieve a specific page of DeviceSecretInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceSecretInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DeviceSecretPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> DeviceSecretPage: - """ - Asynchronously retrieve a specific page of DeviceSecretInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeviceSecretInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DeviceSecretPage(self._version, response, self._solution) - - def get(self, key: str) -> DeviceSecretContext: - """ - Constructs a DeviceSecretContext - - :param key: The secret key; up to 100 characters. - """ - return DeviceSecretContext( - self._version, device_sid=self._solution["device_sid"], key=key - ) - - def __call__(self, key: str) -> DeviceSecretContext: - """ - Constructs a DeviceSecretContext - - :param key: The secret key; up to 100 characters. - """ - return DeviceSecretContext( - self._version, device_sid=self._solution["device_sid"], key=key - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Microvisor.V1.DeviceSecretList>" diff --git a/twilio/rest/monitor/v1/alert.py b/twilio/rest/monitor/v1/alert.py index 829e633643..f7666a0e3b 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AlertContext] = None @property @@ -114,6 +116,24 @@ async def fetch_async(self) -> "AlertInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,48 +161,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Alerts/{sid}".format(**self._solution) - def fetch(self) -> AlertInstance: + def _fetch(self) -> tuple: """ - Fetch the AlertInstance - + Internal helper for fetch operation - :returns: The fetched AlertInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlertInstance: + """ + Fetch the AlertInstance + + :returns: The fetched AlertInstance + """ + payload, _, _ = self._fetch() return AlertInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AlertInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AlertInstance + Fetch the AlertInstance and return response metadata - :returns: The fetched AlertInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AlertInstance: + """ + Asynchronous coroutine to fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + payload, _, _ = await self._fetch_async() return AlertInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlertInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +269,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: :param payload: Payload response from the API """ + return AlertInstance(self._version, payload) def __repr__(self) -> str: @@ -297,6 +366,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AlertInstance and returns headers from first page + + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AlertInstance and returns headers from first page + + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, log_level: Union[str, object] = values.unset, @@ -322,6 +461,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log_level=log_level, @@ -357,6 +497,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -368,6 +509,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AlertInstance and returns headers from first page + + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AlertInstance and returns headers from first page + + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, log_level: Union[str, object] = values.unset, @@ -452,6 +661,94 @@ async def page_async( ) return AlertPage(self._version, response) + def page_with_http_info( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlertPage, status code, and headers + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AlertPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AlertPage, status code, and headers + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AlertPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AlertPage: """ Retrieve a specific page of AlertInstance records from the API. diff --git a/twilio/rest/monitor/v1/event.py b/twilio/rest/monitor/v1/event.py index 31716b8813..e568c814e1 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,7 +26,7 @@ class EventInstance(InstanceResource): """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. - :ivar actor_sid: The SID of the actor that caused the event, if available. Can be `null`. + :ivar actor_sid: The SID of the actor that caused the event, if available. This can be either a User ID (matching the pattern `^US[0-9a-fA-F]{32}$`) or an Account SID (matching the pattern `^AC[0-9a-fA-F]{32}$`). If the actor's SID isn't available, this field will be `null`. :ivar actor_type: The type of actor that caused the event. Can be: `user` for a change made by a logged-in user in the Twilio Console, `account` for an event caused by an API request by an authenticating Account, `twilio-admin` for an event caused by a Twilio employee, and so on. :ivar description: A description of the event. Can be `null`. :ivar event_data: An object with additional data about the event. The contents depend on `event_type`. For example, event-types of the form `RESOURCE.updated`, this value contains a `resource_properties` dictionary that describes the previous and updated properties of the resource. @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -100,6 +102,24 @@ async def fetch_async(self) -> "EventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -127,48 +147,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Events/{sid}".format(**self._solution) - def fetch(self) -> EventInstance: + def _fetch(self) -> tuple: """ - Fetch the EventInstance - + Internal helper for fetch operation - :returns: The fetched EventInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + :returns: The fetched EventInstance + """ + payload, _, _ = self._fetch() return EventInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EventInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EventInstance + Fetch the EventInstance and return response metadata - :returns: The fetched EventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + payload, _, _ = await self._fetch_async() return EventInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -187,6 +255,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance(self._version, payload) def __repr__(self) -> str: @@ -301,6 +370,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, actor_sid: Union[str, object] = values.unset, @@ -332,6 +489,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( actor_sid=actor_sid, @@ -376,6 +534,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -390,6 +549,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, actor_sid: Union[str, object] = values.unset, @@ -492,6 +737,112 @@ async def page_async( ) return EventPage(self._version, response) + def page_with_http_info( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EventPage: """ Retrieve a specific page of EventInstance records from the API. diff --git a/twilio/rest/notify/v1/credential.py b/twilio/rest/notify/v1/credential.py index 9ca59927cb..9bbd8bd0fc 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,10 +320,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,56 +354,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + :returns: The fetched CredentialInstance + """ + payload, _, _ = self._fetch() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialInstance + Fetch the CredentialInstance and return response metadata - :returns: The fetched CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -277,18 +465,12 @@ def update( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Update the CredentialInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` - :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -307,13 +489,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, certificate: Union[str, object] = values.unset, @@ -323,7 +503,7 @@ async def update_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronous coroutine to update the CredentialInstance + Update the CredentialInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` @@ -334,6 +514,63 @@ async def update_async( :returns: The updated CredentialInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -351,12 +588,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -375,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -399,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -408,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance - - :param type: - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` - :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + Internal helper for create operation - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -440,13 +732,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -457,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -469,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -487,12 +839,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -543,6 +962,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -562,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -588,6 +1058,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -596,6 +1067,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -662,6 +1183,76 @@ async def page_async( ) return CredentialPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CredentialPage: """ Retrieve a specific page of CredentialInstance records from the API. diff --git a/twilio/rest/notify/v1/service/__init__.py b/twilio/rest/notify/v1/service/__init__.py index e097e69a67..629a7f2ae2 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -93,6 +94,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -128,6 +130,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -146,6 +166,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -254,6 +292,114 @@ async def update_async( delivery_callback_enabled=delivery_callback_enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + @property def bindings(self) -> BindingList: """ @@ -298,6 +444,20 @@ def __init__(self, version: Version, sid: str): self._bindings: Optional[BindingList] = None self._notifications: Optional[NotificationList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -305,10 +465,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -317,56 +499,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -382,26 +618,12 @@ def update( default_alexa_notification_protocol_version: Union[str, object] = values.unset, delivery_callback_url: Union[str, object] = values.unset, delivery_callback_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. - :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. - :param facebook_messenger_page_id: Deprecated. - :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. - :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. - :param alexa_skill_id: Deprecated. - :param default_alexa_notification_protocol_version: Deprecated. - :param delivery_callback_url: URL to send delivery status callback. - :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -430,13 +652,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -454,7 +674,7 @@ async def update_async( delivery_callback_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. @@ -473,44 +693,250 @@ async def update_async( :returns: The updated ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ApnCredentialSid": apn_credential_sid, - "GcmCredentialSid": gcm_credential_sid, - "MessagingServiceSid": messaging_service_sid, - "FacebookMessengerPageId": facebook_messenger_page_id, - "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, - "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, - "FcmCredentialSid": fcm_credential_sid, - "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, - "LogEnabled": serialize.boolean_to_string(log_enabled), - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": serialize.boolean_to_string( - delivery_callback_enabled - ), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - @property - def bindings(self) -> BindingList: - """ - Access the bindings - """ + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ if self._bindings is None: self._bindings = BindingList( self._version, @@ -548,6 +974,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -572,7 +999,172 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -588,26 +1180,12 @@ def create( default_alexa_notification_protocol_version: Union[str, object] = values.unset, delivery_callback_url: Union[str, object] = values.unset, delivery_callback_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. - :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. - :param facebook_messenger_page_id: Deprecated. - :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. - :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. - :param alexa_skill_id: Deprecated. - :param default_alexa_notification_protocol_version: Deprecated. - :param delivery_callback_url: URL to send delivery status callback. - :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + Internal async helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -636,12 +1214,10 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - async def create_async( self, friendly_name: Union[str, object] = values.unset, @@ -679,38 +1255,79 @@ async def create_async( :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ApnCredentialSid": apn_credential_sid, - "GcmCredentialSid": gcm_credential_sid, - "MessagingServiceSid": messaging_service_sid, - "FacebookMessengerPageId": facebook_messenger_page_id, - "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, - "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, - "FcmCredentialSid": fcm_credential_sid, - "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, - "LogEnabled": serialize.boolean_to_string(log_enabled), - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": serialize.boolean_to_string( - delivery_callback_enabled - ), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return ServiceInstance(self._version, payload) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata - headers["Accept"] = "application/json" + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, ) - - return ServiceInstance(self._version, payload) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -768,6 +1385,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -789,6 +1462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -818,6 +1492,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -827,6 +1502,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -899,6 +1630,82 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/notify/v1/service/binding.py b/twilio/rest/notify/v1/service/binding.py index 33b1a4aac0..e380730645 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -173,10 +225,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -185,27 +259,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BindingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BindingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BindingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = self._fetch() return BindingInstance( self._version, payload, @@ -213,22 +303,46 @@ def fetch(self) -> BindingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> BindingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BindingInstance + Fetch the BindingInstance and return response metadata - :returns: The fetched BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + payload, _, _ = await self._fetch_async() return BindingInstance( self._version, payload, @@ -236,6 +350,22 @@ async def fetch_async(self) -> BindingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -254,6 +384,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -285,7 +416,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) - def create( + def _create( self, identity: str, binding_type: "BindingInstance.BindingType", @@ -294,19 +425,12 @@ def create( notification_protocol_version: Union[str, object] = values.unset, credential_sid: Union[str, object] = values.unset, endpoint: Union[str, object] = values.unset, - ) -> BindingInstance: + ) -> tuple: """ - Create the BindingInstance - - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. - :param binding_type: - :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. - :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. - :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. - :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. - :param endpoint: Deprecated. + Internal helper for create operation - :returns: The created BindingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,15 +450,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + payload, _, _ = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, binding_type: "BindingInstance.BindingType", @@ -343,9 +499,9 @@ async def create_async( notification_protocol_version: Union[str, object] = values.unset, credential_sid: Union[str, object] = values.unset, endpoint: Union[str, object] = values.unset, - ) -> BindingInstance: + ) -> ApiResponse: """ - Asynchronously create the BindingInstance + Create the BindingInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. :param binding_type: @@ -355,7 +511,37 @@ async def create_async( :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. :param endpoint: Deprecated. - :returns: The created BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -375,14 +561,83 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Asynchronously create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BindingInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, start_date: Union[date, object] = values.unset, @@ -461,6 +716,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, start_date: Union[date, object] = values.unset, @@ -488,6 +819,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -526,6 +858,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -538,6 +871,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BindingInstance and returns headers from first page + + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, start_date: Union[date, object] = values.unset, @@ -581,7 +988,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -626,7 +1033,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BindingPage, status code, and headers + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BindingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BindingPage: """ @@ -638,7 +1139,7 @@ def get_page(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BindingPage: """ @@ -650,7 +1151,7 @@ async def get_page_async(self, target_url: str) -> BindingPage: :returns: Page of BindingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BindingPage(self._version, response, self._solution) + return BindingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> BindingContext: """ diff --git a/twilio/rest/notify/v1/service/notification.py b/twilio/rest/notify/v1/service/notification.py index 4d228e864f..a16ef7acf1 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -112,7 +113,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Notifications".format(**self._solution) - def create( + def _create( self, body: Union[str, object] = values.unset, priority: Union["NotificationInstance.Priority", object] = values.unset, @@ -132,30 +133,12 @@ def create( delivery_callback_url: Union[str, object] = values.unset, identity: Union[List[str], object] = values.unset, tag: Union[List[str], object] = values.unset, - ) -> NotificationInstance: + ) -> tuple: """ - Create the NotificationInstance - - :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. - :param priority: - :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. - :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. - :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. - :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. - :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. - :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. - :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). - :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. - :param facebook_messenger: Deprecated. - :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. - :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. - :param alexa: Deprecated. - :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. - :param delivery_callback_url: URL to send webhooks. - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. - :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + Internal helper for create operation - :returns: The created NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -186,15 +169,80 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + payload, _, _ = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) return NotificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, body: Union[str, object] = values.unset, priority: Union["NotificationInstance.Priority", object] = values.unset, @@ -214,9 +262,9 @@ async def create_async( delivery_callback_url: Union[str, object] = values.unset, identity: Union[List[str], object] = values.unset, tag: Union[List[str], object] = values.unset, - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronously create the NotificationInstance + Create the NotificationInstance and return response metadata :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. :param priority: @@ -237,7 +285,59 @@ async def create_async( :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. - :returns: The created NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -268,14 +368,149 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + payload, _, _ = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) return NotificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NotificationInstance and return response metadata + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/NumbersBase.py b/twilio/rest/numbers/NumbersBase.py index 7b9e08638f..d7b4b3ee8e 100644 --- a/twilio/rest/numbers/NumbersBase.py +++ b/twilio/rest/numbers/NumbersBase.py @@ -15,6 +15,7 @@ from twilio.rest import Client from twilio.rest.numbers.v1 import V1 from twilio.rest.numbers.v2 import V2 +from twilio.rest.numbers.v3 import V3 class NumbersBase(Domain): @@ -28,6 +29,7 @@ def __init__(self, twilio: Client): super().__init__(twilio, "https://numbers.twilio.com") self._v1: Optional[V1] = None self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -47,6 +49,15 @@ def v2(self) -> V2: self._v2 = V2(self) return self._v2 + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Numbers + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/__init__.py b/twilio/rest/numbers/v1/__init__.py index 68f078a88d..a3f3cc0847 100644 --- a/twilio/rest/numbers/v1/__init__.py +++ b/twilio/rest/numbers/v1/__init__.py @@ -17,6 +17,8 @@ from twilio.base.domain import Domain from twilio.rest.numbers.v1.bulk_eligibility import BulkEligibilityList from twilio.rest.numbers.v1.eligibility import EligibilityList +from twilio.rest.numbers.v1.embedded_session import EmbeddedSessionList +from twilio.rest.numbers.v1.porting_all_port_in import PortingAllPortInList from twilio.rest.numbers.v1.porting_port_in import PortingPortInList from twilio.rest.numbers.v1.porting_port_in_phone_number import ( PortingPortInPhoneNumberList, @@ -28,6 +30,7 @@ from twilio.rest.numbers.v1.porting_webhook_configuration_delete import ( PortingWebhookConfigurationDeleteList, ) +from twilio.rest.numbers.v1.sender_id_registration import SenderIdRegistrationList from twilio.rest.numbers.v1.signing_request_configuration import ( SigningRequestConfigurationList, ) @@ -45,6 +48,7 @@ def __init__(self, domain: Domain): super().__init__(domain, "v1") self._bulk_eligibilities: Optional[BulkEligibilityList] = None self._eligibilities: Optional[EligibilityList] = None + self._porting_all_port_ins: Optional[PortingAllPortInList] = None self._porting_port_ins: Optional[PortingPortInList] = None self._porting_port_in_phone_number: Optional[PortingPortInPhoneNumberList] = ( None @@ -56,6 +60,7 @@ def __init__(self, domain: Domain): self._porting_webhook_configurations_delete: Optional[ PortingWebhookConfigurationDeleteList ] = None + self._sender_id_registrations: Optional[SenderIdRegistrationList] = None self._signing_request_configurations: Optional[ SigningRequestConfigurationList ] = None @@ -73,6 +78,26 @@ def eligibilities(self) -> EligibilityList: self._eligibilities = EligibilityList(self) return self._eligibilities + def embedded_sessions(self, bundle_sid: str, embedded_session_id: str = None): + """ + Access the EmbeddedSessionList resource + + :param bundle_sid: The unique identifier of the registration (BU-prefixed). + + :param embedded_session_id: Optional instance ID to directly access EmbeddedSessionContext + :returns: EmbeddedSessionList instance if embedded_session_id is None, otherwise EmbeddedSessionContext + """ + list_instance = EmbeddedSessionList(self, bundle_sid) + if embedded_session_id is not None: + return list_instance(embedded_session_id) + return list_instance + + @property + def porting_all_port_ins(self) -> PortingAllPortInList: + if self._porting_all_port_ins is None: + self._porting_all_port_ins = PortingAllPortInList(self) + return self._porting_all_port_ins + @property def porting_port_ins(self) -> PortingPortInList: if self._porting_port_ins is None: @@ -107,6 +132,12 @@ def porting_webhook_configurations_delete( ) return self._porting_webhook_configurations_delete + @property + def sender_id_registrations(self) -> SenderIdRegistrationList: + if self._sender_id_registrations is None: + self._sender_id_registrations = SenderIdRegistrationList(self) + return self._sender_id_registrations + @property def signing_request_configurations(self) -> SigningRequestConfigurationList: if self._signing_request_configurations is None: diff --git a/twilio/rest/numbers/v1/bulk_eligibility.py b/twilio/rest/numbers/v1/bulk_eligibility.py index 766032f7c4..ed521218a5 100644 --- a/twilio/rest/numbers/v1/bulk_eligibility.py +++ b/twilio/rest/numbers/v1/bulk_eligibility.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "request_id": request_id or self.request_id, } + self._context: Optional[BulkEligibilityContext] = None @property @@ -90,6 +92,24 @@ async def fetch_async(self) -> "BulkEligibilityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,48 +139,96 @@ def __init__(self, version: Version, request_id: str): **self._solution ) - def fetch(self) -> BulkEligibilityInstance: + def _fetch(self) -> tuple: """ - Fetch the BulkEligibilityInstance - + Internal helper for fetch operation - :returns: The fetched BulkEligibilityInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BulkEligibilityInstance: + """ + Fetch the BulkEligibilityInstance + + :returns: The fetched BulkEligibilityInstance + """ + payload, _, _ = self._fetch() return BulkEligibilityInstance( self._version, payload, request_id=self._solution["request_id"], ) - async def fetch_async(self) -> BulkEligibilityInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BulkEligibilityInstance + Fetch the BulkEligibilityInstance and return response metadata - :returns: The fetched BulkEligibilityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BulkEligibilityInstance: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + payload, _, _ = await self._fetch_async() return BulkEligibilityInstance( self._version, payload, request_id=self._solution["request_id"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -184,15 +252,12 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/Eligibility/Bulk" - def create( - self, body: Union[object, object] = values.unset - ) -> BulkEligibilityInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the BulkEligibilityInstance - - :param body: + Internal helper for create operation - :returns: The created BulkEligibilityInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -202,22 +267,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return BulkEligibilityInstance(self._version, payload) - - async def create_async( + def create( self, body: Union[object, object] = values.unset ) -> BulkEligibilityInstance: """ - Asynchronously create the BulkEligibilityInstance + Create the BulkEligibilityInstance :param body: :returns: The created BulkEligibilityInstance """ + payload, _, _ = self._create(body=body) + return BulkEligibilityInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the BulkEligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = BulkEligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = body.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -226,12 +313,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Asynchronously create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + payload, _, _ = await self._create_async(body=body) return BulkEligibilityInstance(self._version, payload) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkEligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = BulkEligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, request_id: str) -> BulkEligibilityContext: """ Constructs a BulkEligibilityContext diff --git a/twilio/rest/numbers/v1/eligibility.py b/twilio/rest/numbers/v1/eligibility.py index 8c5af0ac64..37d6f1c07d 100644 --- a/twilio/rest/numbers/v1/eligibility.py +++ b/twilio/rest/numbers/v1/eligibility.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,13 +54,12 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/Eligibility" - def create(self, body: Union[object, object] = values.unset) -> EligibilityInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the EligibilityInstance + Internal helper for create operation - :param body: - - :returns: The created EligibilityInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -69,21 +69,41 @@ def create(self, body: Union[object, object] = values.unset) -> EligibilityInsta headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, body: Union[object, object] = values.unset) -> EligibilityInstance: + """ + Create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + payload, _, _ = self._create(body=body) return EligibilityInstance(self._version, payload) - async def create_async( + def create_with_http_info( self, body: Union[object, object] = values.unset - ) -> EligibilityInstance: + ) -> ApiResponse: """ - Asynchronously create the EligibilityInstance + Create the EligibilityInstance and return response metadata :param body: - :returns: The created EligibilityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = EligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -93,12 +113,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> EligibilityInstance: + """ + Asynchronously create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + payload, _, _ = await self._create_async(body=body) return EligibilityInstance(self._version, payload) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EligibilityInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = EligibilityInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/embedded_session.py b/twilio/rest/numbers/v1/embedded_session.py new file mode 100644 index 0000000000..d047adc2ab --- /dev/null +++ b/twilio/rest/numbers/v1/embedded_session.py @@ -0,0 +1,230 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EmbeddedSessionInstance(InstanceResource): + + class NumbersV1CreateEmbeddedSessionRequest(object): + """ + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. Overrides the theme set during registration creation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.theme_set_id: Optional[str] = payload.get("themeSetId") + + def to_dict(self): + return { + "themeSetId": self.theme_set_id, + } + + """ + :ivar id: Registration identifier (BU-prefixed). + :ivar session_id: Session ID for the compliance embeddable. + :ivar session_token: Ephemeral session token for the compliance embeddable. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + self._solution = { + "bundle_sid": bundle_sid or self.bundle_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.EmbeddedSessionInstance {}>".format(context) + + +class EmbeddedSessionList(ListResource): + + class NumbersV1CreateEmbeddedSessionRequest(object): + """ + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. Overrides the theme set during registration creation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.theme_set_id: Optional[str] = payload.get("themeSetId") + + def to_dict(self): + return { + "themeSetId": self.theme_set_id, + } + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the EmbeddedSessionList + + :param version: Version that contains the resource + :param bundle_sid: The unique identifier of the registration (BU-prefixed). + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/SenderIdRegistrations/{bundle_sid}/EmbeddedSessions".format( + **self._solution + ) + + def _create( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_session_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> EmbeddedSessionInstance: + """ + Create the EmbeddedSessionInstance + + :param numbers_v1_create_embedded_session_request: + + :returns: The created EmbeddedSessionInstance + """ + payload, _, _ = self._create( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + return EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> ApiResponse: + """ + Create the EmbeddedSessionInstance and return response metadata + + :param numbers_v1_create_embedded_session_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + instance = EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_session_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> EmbeddedSessionInstance: + """ + Asynchronously create the EmbeddedSessionInstance + + :param numbers_v1_create_embedded_session_request: + + :returns: The created EmbeddedSessionInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + return EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_with_http_info_async( + self, + numbers_v1_create_embedded_session_request: NumbersV1CreateEmbeddedSessionRequest, + ) -> ApiResponse: + """ + Asynchronously create the EmbeddedSessionInstance and return response metadata + + :param numbers_v1_create_embedded_session_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_create_embedded_session_request=numbers_v1_create_embedded_session_request + ) + instance = EmbeddedSessionInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.EmbeddedSessionList>" diff --git a/twilio/rest/numbers/v1/porting_all_port_in.py b/twilio/rest/numbers/v1/porting_all_port_in.py new file mode 100644 index 0000000000..3a2df49b13 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_all_port_in.py @@ -0,0 +1,689 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PortingAllPortInInstance(InstanceResource): + """ + :ivar port_in_request_sid: The SID of the Port-in request + :ivar port_in_request_status: Status of the Port In Request + :ivar status_last_updated_timestamp: The last updated timestamp of the request + :ivar phone_numbers_requested: Amount of phone numbers requested + :ivar phone_numbers_ported: Amount of phone numbers ported + :ivar suggested_action: Suggested action on this ticket + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.port_in_request_status: Optional[str] = payload.get( + "port_in_request_status" + ) + self.status_last_updated_timestamp: Optional[str] = payload.get( + "status_last_updated_timestamp" + ) + self.phone_numbers_requested: Optional[int] = deserialize.integer( + payload.get("phone_numbers_requested") + ) + self.phone_numbers_ported: Optional[int] = deserialize.integer( + payload.get("phone_numbers_ported") + ) + self.suggested_action: Optional[str] = payload.get("suggested_action") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.PortingAllPortInInstance>" + + +class PortingAllPortInPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PortingAllPortInInstance: + """ + Build an instance of PortingAllPortInInstance + + :param payload: Payload response from the API + """ + + return PortingAllPortInInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingAllPortInPage>" + + +class PortingAllPortInList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingAllPortInList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/PortIn/PortInRequests" + + def stream( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PortingAllPortInInstance]: + """ + Streams PortingAllPortInInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PortingAllPortInInstance]: + """ + Asynchronously streams PortingAllPortInInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PortingAllPortInInstance]: + """ + Lists PortingAllPortInInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PortingAllPortInInstance]: + """ + Asynchronously lists PortingAllPortInInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PortingAllPortInInstance and returns headers from first page + + + :param str token: Page start token, if null then it will start from the beginning + :param int size: Number of items per page + :param str port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param str port_in_request_status: Filter by Port In request status + :param str created_before: Find all created before a certain date + :param str created_after: Find all created after a certain date + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + token=token, + size=size, + port_in_request_sid=port_in_request_sid, + port_in_request_status=port_in_request_status, + created_before=created_before, + created_after=created_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PortingAllPortInPage: + """ + Retrieve a single page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain date + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PortingAllPortInInstance + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": created_after, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PortingAllPortInPage(self._version, response) + + async def page_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PortingAllPortInPage: + """ + Asynchronously retrieve a single page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain date + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PortingAllPortInInstance + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": created_after, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PortingAllPortInPage(self._version, response) + + def page_with_http_info( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain date + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PortingAllPortInPage, status code, and headers + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": created_after, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PortingAllPortInPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + token: Union[str, object] = values.unset, + size: Union[int, object] = values.unset, + port_in_request_sid: Union[str, object] = values.unset, + port_in_request_status: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param token: Page start token, if null then it will start from the beginning + :param size: Number of items per page + :param port_in_request_sid: Filter by Port in request SID, supports multiple values separated by comma + :param port_in_request_status: Filter by Port In request status + :param created_before: Find all created before a certain date + :param created_after: Find all created after a certain date + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PortingAllPortInPage, status code, and headers + """ + data = values.of( + { + "Token": token, + "Size": size, + "PortInRequestSid": port_in_request_sid, + "PortInRequestStatus": port_in_request_status, + "CreatedBefore": created_before, + "CreatedAfter": created_after, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PortingAllPortInPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> PortingAllPortInPage: + """ + Retrieve a specific page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PortingAllPortInInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PortingAllPortInPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PortingAllPortInPage: + """ + Asynchronously retrieve a specific page of PortingAllPortInInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PortingAllPortInInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PortingAllPortInPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingAllPortInList>" diff --git a/twilio/rest/numbers/v1/porting_port_in.py b/twilio/rest/numbers/v1/porting_port_in.py index bfca5762e0..53400a5fd0 100644 --- a/twilio/rest/numbers/v1/porting_port_in.py +++ b/twilio/rest/numbers/v1/porting_port_in.py @@ -13,8 +13,9 @@ """ from datetime import date, datetime -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,19 +23,199 @@ class PortingPortInInstance(InstanceResource): + + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + """ :ivar port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. :ivar url: The URL of this Port In request :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported :ivar notification_emails: Additional emails to send a copy of the signed LOA to. - :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. (This value is only available for custom porting customers.) - :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. (This value is only available for custom porting customers.) - :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. (This value is only available for custom porting customers.) + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. If a start and end range is provided, the date will be converted to its UTC equivalent with the ranges as reference and stored in UTC. We can't guarantee the exact date and time, as this depends on the losing carrier. + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier. The time will be stored and returned as UTC standard timezone. + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier. The time will be stored and returned as UTC standard timezone. :ivar port_in_request_status: The status of the port in request. The possible values are: In progress, Completed, Expired, In review, Waiting for Signature, Action Required, and Canceled. - :ivar losing_carrier_information: Details regarding the customer’s information with the losing carrier. These values will be used to generate the letter of authorization and should match the losing carrier’s data as closely as possible to ensure the port is accepted. - :ivar phone_numbers: + :ivar order_cancellation_reason: If the order is cancelled this field will provide further context on the cause of the cancellation. + :ivar losing_carrier_information: + :ivar phone_numbers: + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. - :ivar date_created: + :ivar date_created: + :ivar support_ticket_id: Unique ID of the request's support ticket + :ivar signature_request_url: """ def __init__( @@ -63,20 +244,33 @@ def __init__( self.port_in_request_status: Optional[str] = payload.get( "port_in_request_status" ) - self.losing_carrier_information: Optional[Dict[str, object]] = payload.get( + self.order_cancellation_reason: Optional[str] = payload.get( + "order_cancellation_reason" + ) + self.losing_carrier_information: Optional[str] = payload.get( "losing_carrier_information" ) - self.phone_numbers: Optional[List[Dict[str, object]]] = payload.get( - "phone_numbers" + self.phone_numbers: Optional[List[str]] = payload.get("phone_numbers") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" ) self.documents: Optional[List[str]] = payload.get("documents") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) + self.support_ticket_id: Optional[int] = deserialize.integer( + payload.get("support_ticket_id") + ) + self.signature_request_url: Optional[str] = payload.get("signature_request_url") self._solution = { "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, } + self._context: Optional[PortingPortInContext] = None @property @@ -112,6 +306,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PortingPortInInstance": """ Fetch the PortingPortInInstance @@ -130,6 +342,24 @@ async def fetch_async(self) -> "PortingPortInInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,6 +372,179 @@ def __repr__(self) -> str: class PortingPortInContext(InstanceContext): + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + def __init__(self, version: Version, port_in_request_sid: str): """ Initialize the PortingPortInContext @@ -157,6 +560,20 @@ def __init__(self, version: Version, port_in_request_sid: str): } self._uri = "/Porting/PortIn/{port_in_request_sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingPortInInstance @@ -164,10 +581,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -176,55 +615,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PortingPortInInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PortingPortInInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PortingPortInInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInInstance: + """ + Fetch the PortingPortInInstance + + :returns: The fetched PortingPortInInstance + """ + payload, _, _ = self._fetch() return PortingPortInInstance( self._version, payload, port_in_request_sid=self._solution["port_in_request_sid"], ) - async def fetch_async(self) -> PortingPortInInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PortingPortInInstance + Fetch the PortingPortInInstance and return response metadata - :returns: The fetched PortingPortInInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PortingPortInInstance: + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + payload, _, _ = await self._fetch_async() return PortingPortInInstance( self._version, payload, port_in_request_sid=self._solution["port_in_request_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -237,6 +730,179 @@ def __repr__(self) -> str: class PortingPortInList(ListResource): + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + def __init__(self, version: Version): """ Initialize the PortingPortInList @@ -248,17 +914,16 @@ def __init__(self, version: Version): self._uri = "/Porting/PortIn" - def create( - self, body: Union[object, object] = values.unset - ) -> PortingPortInInstance: + def _create( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: """ - Create the PortingPortInInstance + Internal helper for create operation - :param body: - - :returns: The created PortingPortInInstance + Returns: + tuple: (payload, status_code, headers) """ - data = body.to_dict() + data = numbers_v1_porting_port_in_create.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -266,23 +931,51 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PortingPortInInstance(self._version, payload) - - async def create_async( - self, body: Union[object, object] = values.unset + def create( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate ) -> PortingPortInInstance: """ - Asynchronously create the PortingPortInInstance + Create the PortingPortInInstance - :param body: + :param numbers_v1_porting_port_in_create: :returns: The created PortingPortInInstance """ - data = body.to_dict() + payload, _, _ = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + return PortingPortInInstance(self._version, payload) + + def create_with_http_info( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Create the PortingPortInInstance and return response metadata + + :param numbers_v1_porting_port_in_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + instance = PortingPortInInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_porting_port_in_create.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -290,12 +983,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> PortingPortInInstance: + """ + Asynchronously create the PortingPortInInstance + + :param numbers_v1_porting_port_in_create: + + :returns: The created PortingPortInInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) return PortingPortInInstance(self._version, payload) + async def create_with_http_info_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Asynchronously create the PortingPortInInstance and return response metadata + + :param numbers_v1_porting_port_in_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + instance = PortingPortInInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, port_in_request_sid: str) -> PortingPortInContext: """ Constructs a PortingPortInContext diff --git a/twilio/rest/numbers/v1/porting_port_in_phone_number.py b/twilio/rest/numbers/v1/porting_port_in_phone_number.py index cc8120f78f..1efa19ebe8 100644 --- a/twilio/rest/numbers/v1/porting_port_in_phone_number.py +++ b/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -93,6 +94,7 @@ def __init__( "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, "phone_number_sid": phone_number_sid or self.phone_number_sid, } + self._context: Optional[PortingPortInPhoneNumberContext] = None @property @@ -129,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PortingPortInPhoneNumberInstance": """ Fetch the PortingPortInPhoneNumberInstance @@ -147,6 +167,24 @@ async def fetch_async(self) -> "PortingPortInPhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -180,6 +218,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingPortInPhoneNumberInstance @@ -187,10 +239,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -199,27 +273,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PortingPortInPhoneNumberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PortingPortInPhoneNumberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PortingPortInPhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInPhoneNumberInstance: + """ + Fetch the PortingPortInPhoneNumberInstance + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + payload, _, _ = self._fetch() return PortingPortInPhoneNumberInstance( self._version, payload, @@ -227,22 +317,46 @@ def fetch(self) -> PortingPortInPhoneNumberInstance: phone_number_sid=self._solution["phone_number_sid"], ) - async def fetch_async(self) -> PortingPortInPhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + Fetch the PortingPortInPhoneNumberInstance and return response metadata - :returns: The fetched PortingPortInPhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PortingPortInPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return PortingPortInPhoneNumberInstance( self._version, payload, @@ -250,6 +364,22 @@ async def fetch_async(self) -> PortingPortInPhoneNumberInstance: phone_number_sid=self._solution["phone_number_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/porting_portability.py b/twilio/rest/numbers/v1/porting_portability.py index 351cd541af..5bcc0e604c 100644 --- a/twilio/rest/numbers/v1/porting_portability.py +++ b/twilio/rest/numbers/v1/porting_portability.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PortingPortabilityContext] = None @property @@ -120,6 +122,42 @@ async def fetch_async( address_sid=address_sid, ) + def fetch_with_http_info( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PortingPortabilityInstance with HTTP info + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + async def fetch_with_http_info_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance with HTTP info + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -149,21 +187,19 @@ def __init__(self, version: Version, phone_number: str): **self._solution ) - def fetch( + def _fetch( self, target_account_sid: Union[str, object] = values.unset, address_sid: Union[str, object] = values.unset, - ) -> PortingPortabilityInstance: + ) -> tuple: """ - Fetch the PortingPortabilityInstance + Internal helper for fetch operation - :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. - :param address_sid: Address Sid of customer to which the number will be ported. - - :returns: The fetched PortingPortabilityInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TargetAccountSid": target_account_sid, "AddressSid": address_sid, @@ -174,31 +210,68 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + payload, _, _ = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) return PortingPortabilityInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async( + def fetch_with_http_info( self, target_account_sid: Union[str, object] = values.unset, address_sid: Union[str, object] = values.unset, - ) -> PortingPortabilityInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the PortingPortabilityInstance + Fetch the PortingPortabilityInstance and return response metadata :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. :param address_sid: Address Sid of customer to which the number will be ported. - :returns: The fetched PortingPortabilityInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) + instance = PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TargetAccountSid": target_account_sid, "AddressSid": address_sid, @@ -209,16 +282,55 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + payload, _, _ = await self._fetch_async( + target_account_sid=target_account_sid, address_sid=address_sid + ) return PortingPortabilityInstance( self._version, payload, phone_number=self._solution["phone_number"], ) + async def fetch_with_http_info_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance and return response metadata + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + target_account_sid=target_account_sid, address_sid=address_sid + ) + instance = PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration.py b/twilio/rest/numbers/v1/porting_webhook_configuration.py index cfd9e1d0a8..4769c6ae74 100644 --- a/twilio/rest/numbers/v1/porting_webhook_configuration.py +++ b/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -59,15 +60,12 @@ def __init__(self, version: Version): self._uri = "/Porting/Configuration/Webhook" - def create( - self, body: Union[object, object] = values.unset - ) -> PortingWebhookConfigurationInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the PortingWebhookConfigurationInstance - - :param body: + Internal helper for create operation - :returns: The created PortingWebhookConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -77,22 +75,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return PortingWebhookConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, body: Union[object, object] = values.unset ) -> PortingWebhookConfigurationInstance: """ - Asynchronously create the PortingWebhookConfigurationInstance + Create the PortingWebhookConfigurationInstance :param body: :returns: The created PortingWebhookConfigurationInstance """ + payload, _, _ = self._create(body=body) + return PortingWebhookConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the PortingWebhookConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = PortingWebhookConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = body.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -101,12 +121,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Asynchronously create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + payload, _, _ = await self._create_async(body=body) return PortingWebhookConfigurationInstance(self._version, payload) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the PortingWebhookConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = PortingWebhookConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py index 11572f1846..e724498b0a 100644 --- a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -13,6 +13,7 @@ """ from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.list_resource import ListResource @@ -42,6 +43,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingWebhookConfigurationDeleteInstance @@ -49,10 +64,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingWebhookConfigurationDeleteInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -61,12 +98,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingWebhookConfigurationDeleteInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/numbers/v1/sender_id_registration.py b/twilio/rest/numbers/v1/sender_id_registration.py new file mode 100644 index 0000000000..6995e6a84e --- /dev/null +++ b/twilio/rest/numbers/v1/sender_id_registration.py @@ -0,0 +1,279 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SenderIdRegistrationInstance(InstanceResource): + + class NumbersV1CreateEmbeddedRegistrationRequest(object): + """ + :ivar regulation_id: The regulation for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: Human-readable name for the registration. + :ivar status_notification_email: Email address for registration status notifications. + :ivar status_callback_url: The URL of this resource. + :ivar comments: Additional comments about the registration. + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. + :ivar data: Registration data organized by section (alphanumericSender, business, useCase, authorizedRepresentative, officer, businessAddress). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = payload.get("regulationVersion") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def to_dict(self): + return { + "regulationId": self.regulation_id, + "regulationVersion": self.regulation_version, + "friendlyName": self.friendly_name, + "statusNotificationEmail": self.status_notification_email, + "statusCallbackUrl": self.status_callback_url, + "comments": self.comments, + "themeSetId": self.theme_set_id, + "data": self.data, + } + + """ + :ivar id: Registration identifier (BU-prefixed). + :ivar regulation_id: The regulation ID for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: The friendly name provided in the request. + :ivar status: Registration status. Always DRAFT on creation. + :ivar status_notification_email: Email address for status notifications. + :ivar status_callback_url: Callback URL for status webhooks. + :ivar comments: Additional comments. + :ivar embedded_session: + :ivar data: Registration data echoed from the request. + :ivar date_created: Timestamp of creation. + :ivar date_updated: Timestamp of last update. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = deserialize.integer( + payload.get("regulationVersion") + ) + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status: Optional[str] = payload.get("status") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.embedded_session: Optional[str] = payload.get("embeddedSession") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.SenderIdRegistrationInstance>" + + +class SenderIdRegistrationList(ListResource): + + class NumbersV1CreateEmbeddedRegistrationRequest(object): + """ + :ivar regulation_id: The regulation for this registration. + :ivar regulation_version: The regulation version. + :ivar friendly_name: Human-readable name for the registration. + :ivar status_notification_email: Email address for registration status notifications. + :ivar status_callback_url: The URL of this resource. + :ivar comments: Additional comments about the registration. + :ivar theme_set_id: Theme ID for the Compliance Embeddable UI. + :ivar data: Registration data organized by section (alphanumericSender, business, useCase, authorizedRepresentative, officer, businessAddress). + """ + + def __init__(self, payload: Dict[str, Any]): + + self.regulation_id: Optional[str] = payload.get("regulationId") + self.regulation_version: Optional[int] = payload.get("regulationVersion") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.status_notification_email: Optional[str] = payload.get( + "statusNotificationEmail" + ) + self.status_callback_url: Optional[str] = payload.get("statusCallbackUrl") + self.comments: Optional[str] = payload.get("comments") + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def to_dict(self): + return { + "regulationId": self.regulation_id, + "regulationVersion": self.regulation_version, + "friendlyName": self.friendly_name, + "statusNotificationEmail": self.status_notification_email, + "statusCallbackUrl": self.status_callback_url, + "comments": self.comments, + "themeSetId": self.theme_set_id, + "data": self.data, + } + + def __init__(self, version: Version): + """ + Initialize the SenderIdRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SenderIdRegistrations" + + def _create( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> SenderIdRegistrationInstance: + """ + Create the SenderIdRegistrationInstance + + :param numbers_v1_create_embedded_registration_request: + + :returns: The created SenderIdRegistrationInstance + """ + payload, _, _ = self._create( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + return SenderIdRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> ApiResponse: + """ + Create the SenderIdRegistrationInstance and return response metadata + + :param numbers_v1_create_embedded_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + instance = SenderIdRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_create_embedded_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> SenderIdRegistrationInstance: + """ + Asynchronously create the SenderIdRegistrationInstance + + :param numbers_v1_create_embedded_registration_request: + + :returns: The created SenderIdRegistrationInstance + """ + payload, _, _ = await self._create_async( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + return SenderIdRegistrationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + numbers_v1_create_embedded_registration_request: NumbersV1CreateEmbeddedRegistrationRequest, + ) -> ApiResponse: + """ + Asynchronously create the SenderIdRegistrationInstance and return response metadata + + :param numbers_v1_create_embedded_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + numbers_v1_create_embedded_registration_request=numbers_v1_create_embedded_registration_request + ) + instance = SenderIdRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.SenderIdRegistrationList>" diff --git a/twilio/rest/numbers/v1/signing_request_configuration.py b/twilio/rest/numbers/v1/signing_request_configuration.py index fcfcd7777b..18e6f97003 100644 --- a/twilio/rest/numbers/v1/signing_request_configuration.py +++ b/twilio/rest/numbers/v1/signing_request_configuration.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def get_instance( :param payload: Payload response from the API """ + return SigningRequestConfigurationInstance(self._version, payload) def __repr__(self) -> str: @@ -89,15 +91,12 @@ def __init__(self, version: Version): self._uri = "/SigningRequest/Configuration" - def create( - self, body: Union[object, object] = values.unset - ) -> SigningRequestConfigurationInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the SigningRequestConfigurationInstance - - :param body: + Internal helper for create operation - :returns: The created SigningRequestConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -107,22 +106,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SigningRequestConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, body: Union[object, object] = values.unset ) -> SigningRequestConfigurationInstance: """ - Asynchronously create the SigningRequestConfigurationInstance + Create the SigningRequestConfigurationInstance :param body: :returns: The created SigningRequestConfigurationInstance """ + payload, _, _ = self._create(body=body) + return SigningRequestConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the SigningRequestConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = SigningRequestConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = body.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -131,12 +152,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Asynchronously create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + payload, _, _ = await self._create_async(body=body) return SigningRequestConfigurationInstance(self._version, payload) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the SigningRequestConfigurationInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = SigningRequestConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, country: Union[str, object] = values.unset, @@ -199,6 +245,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SigningRequestConfigurationInstance and returns headers from first page + + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + country=country, product=product, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SigningRequestConfigurationInstance and returns headers from first page + + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + country=country, product=product, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, country: Union[str, object] = values.unset, @@ -222,6 +328,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( country=country, @@ -254,6 +361,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -264,6 +372,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SigningRequestConfigurationInstance and returns headers from first page + + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SigningRequestConfigurationInstance and returns headers from first page + + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, country: Union[str, object] = values.unset, @@ -342,6 +512,88 @@ async def page_async( ) return SigningRequestConfigurationPage(self._version, response) + def page_with_http_info( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SigningRequestConfigurationPage, status code, and headers + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SigningRequestConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SigningRequestConfigurationPage, status code, and headers + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SigningRequestConfigurationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SigningRequestConfigurationPage: """ Retrieve a specific page of SigningRequestConfigurationInstance records from the API. diff --git a/twilio/rest/numbers/v1/webhook.py b/twilio/rest/numbers/v1/webhook.py index 69bd556326..c5c9783f7f 100644 --- a/twilio/rest/numbers/v1/webhook.py +++ b/twilio/rest/numbers/v1/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,38 +69,78 @@ def __init__(self, version: Version): self._uri = "/Porting/Configuration/Webhook" - def fetch(self) -> WebhookInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the WebhookInstance + Internal helper for fetch operation - - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance(self._version, payload) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronously fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance(self._version, payload) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v2/__init__.py b/twilio/rest/numbers/v2/__init__.py index 04b303486e..e4f3060250 100644 --- a/twilio/rest/numbers/v2/__init__.py +++ b/twilio/rest/numbers/v2/__init__.py @@ -15,6 +15,7 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.numbers.v2.application import ApplicationList from twilio.rest.numbers.v2.authorization_document import AuthorizationDocumentList from twilio.rest.numbers.v2.bulk_hosted_number_order import BulkHostedNumberOrderList from twilio.rest.numbers.v2.bundle_clone import BundleCloneList @@ -31,12 +32,19 @@ def __init__(self, domain: Domain): :param domain: The Twilio.numbers domain """ super().__init__(domain, "v2") + self._applications: Optional[ApplicationList] = None self._authorization_documents: Optional[AuthorizationDocumentList] = None self._bulk_hosted_number_orders: Optional[BulkHostedNumberOrderList] = None self._bundle_clone: Optional[BundleCloneList] = None self._hosted_number_orders: Optional[HostedNumberOrderList] = None self._regulatory_compliance: Optional[RegulatoryComplianceList] = None + @property + def applications(self) -> ApplicationList: + if self._applications is None: + self._applications = ApplicationList(self) + return self._applications + @property def authorization_documents(self) -> AuthorizationDocumentList: if self._authorization_documents is None: diff --git a/twilio/rest/numbers/v2/application.py b/twilio/rest/numbers/v2/application.py new file mode 100644 index 0000000000..1381c1d7a2 --- /dev/null +++ b/twilio/rest/numbers/v2/application.py @@ -0,0 +1,1166 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ApplicationInstance(InstanceResource): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + """ + :ivar sid: The unique identifier of the Short Code Application. + :ivar application_requirements_sid: The Application Requirements SID. + :ivar application_requirements_version: The version of the application requirements. + :ivar account_sid: The Account SID associated with the application. + :ivar bundle_sid: The Bundle SID for regulatory compliance. + :ivar reviewer: The reviewer of the application. + :ivar zendesk_ticket_id: The Zendesk ticket ID associated with the application. + :ivar friendly_name: The friendly name of the application. + :ivar notification_emails: The notification emails for the application. + :ivar iso_country: The ISO country code. + :ivar state: The state of the application. + :ivar setup: + :ivar business_information: + :ivar user_sign_up: + :ivar compliance_keywords: + :ivar content_examples: + :ivar sms_campaign_details: + :ivar date_created: The date and time the application was created. + :ivar date_updated: The date and time the application was last updated. + :ivar created_by: The identity of the user who created the application. + :ivar updated_by: The identity of the user who last updated the application. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.application_requirements_sid: Optional[str] = payload.get( + "application_requirements_sid" + ) + self.application_requirements_version: Optional[int] = deserialize.integer( + payload.get("application_requirements_version") + ) + self.account_sid: Optional[str] = payload.get("account_sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.reviewer: Optional[str] = payload.get("reviewer") + self.zendesk_ticket_id: Optional[str] = payload.get("zendesk_ticket_id") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.iso_country: Optional[str] = payload.get("iso_country") + self.state: Optional["ApplicationInstance.str"] = payload.get("state") + self.setup: Optional[str] = payload.get("setup") + self.business_information: Optional[str] = payload.get("business_information") + self.user_sign_up: Optional[str] = payload.get("user_sign_up") + self.compliance_keywords: Optional[str] = payload.get("compliance_keywords") + self.content_examples: Optional[str] = payload.get("content_examples") + self.sms_campaign_details: Optional[str] = payload.get("sms_campaign_details") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.updated_by: Optional[str] = payload.get("updated_by") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ApplicationContext] = None + + @property + def _proxy(self) -> "ApplicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApplicationContext for this ApplicationInstance + """ + if self._context is None: + self._context = ApplicationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ApplicationInstance": + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApplicationInstance": + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.ApplicationInstance {}>".format(context) + + +class ApplicationContext(InstanceContext): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApplicationContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Short Code Application resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ShortCodes/Applications/{sid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApplicationInstance: + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = self._fetch() + return ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ApplicationInstance: + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + payload, _, _ = await self._fetch_async() + return ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ApplicationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.ApplicationContext {}>".format(context) + + +class ApplicationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: + """ + Build an instance of ApplicationInstance + + :param payload: Payload response from the API + """ + + return ApplicationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.ApplicationPage>" + + +class ApplicationList(ListResource): + + class CreateShortCodeApplicationRequest(object): + """ + :ivar friendly_name: The friendly name for the short code application. + :ivar iso_country: The ISO country code. + :ivar business_information: + :ivar setup: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.business_information: Optional[ + ApplicationList.CreateShortCodeApplicationRequestBusinessInformation + ] = payload.get("business_information") + self.setup: Optional[ + ApplicationList.CreateShortCodeApplicationRequestSetup + ] = payload.get("setup") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "iso_country": self.iso_country, + "business_information": ( + self.business_information.to_dict() + if self.business_information is not None + else None + ), + "setup": self.setup.to_dict() if self.setup is not None else None, + } + + class CreateShortCodeApplicationRequestBusinessInformation(object): + """ + :ivar customer_facing_profile: The Compliance Profile SID for the customer-facing business profile. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_facing_profile: Optional[str] = payload.get( + "customer_facing_profile" + ) + + def to_dict(self): + return { + "customer_facing_profile": self.customer_facing_profile, + } + + class CreateShortCodeApplicationRequestSetup(object): + """ + :ivar charges_apply: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.charges_apply: Optional[bool] = payload.get("charges_apply") + + def to_dict(self): + return { + "charges_apply": self.charges_apply, + } + + def __init__(self, version: Version): + """ + Initialize the ApplicationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ShortCodes/Applications" + + def _create( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_short_code_application_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param create_short_code_application_request: + + :returns: The created ApplicationInstance + """ + payload, _, _ = self._create( + create_short_code_application_request=create_short_code_application_request + ) + return ApplicationInstance(self._version, payload) + + def create_with_http_info( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApiResponse: + """ + Create the ApplicationInstance and return response metadata + + :param create_short_code_application_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_short_code_application_request=create_short_code_application_request + ) + instance = ApplicationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_short_code_application_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApplicationInstance: + """ + Asynchronously create the ApplicationInstance + + :param create_short_code_application_request: + + :returns: The created ApplicationInstance + """ + payload, _, _ = await self._create_async( + create_short_code_application_request=create_short_code_application_request + ) + return ApplicationInstance(self._version, payload) + + async def create_with_http_info_async( + self, create_short_code_application_request: CreateShortCodeApplicationRequest + ) -> ApiResponse: + """ + Asynchronously create the ApplicationInstance and return response metadata + + :param create_short_code_application_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_short_code_application_request=create_short_code_application_request + ) + instance = ApplicationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: + """ + Streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: + """ + Asynchronously streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ApplicationInstance and returns headers from first page + + + :param str account_sid: The Account SID to filter by. + :param str iso_country: The ISO country to filter by. + :param str status: The application status to filter by. + :param str friendly_name: The friendly name to filter by. + :param str sid: The application SID to filter by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + account_sid=account_sid, + iso_country=iso_country, + status=status, + friendly_name=friendly_name, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response) + + async def page_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response) + + def page_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ApplicationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param account_sid: The Account SID to filter by. + :param iso_country: The ISO country to filter by. + :param status: The application status to filter by. + :param friendly_name: The friendly name to filter by. + :param sid: The application SID to filter by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ApplicationPage, status code, and headers + """ + data = values.of( + { + "AccountSid": account_sid, + "IsoCountry": iso_country, + "Status": status, + "FriendlyName": friendly_name, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ApplicationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> ApplicationPage: + """ + Retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ApplicationPage: + """ + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response) + + def get(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The unique string that identifies the Short Code Application resource. + """ + return ApplicationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The unique string that identifies the Short Code Application resource. + """ + return ApplicationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.ApplicationList>" diff --git a/twilio/rest/numbers/v2/authorization_document/__init__.py b/twilio/rest/numbers/v2/authorization_document/__init__.py index 033a32cfd7..8956774fa8 100644 --- a/twilio/rest/numbers/v2/authorization_document/__init__.py +++ b/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AuthorizationDocumentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthorizationDocumentInstance": """ Fetch the AuthorizationDocumentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "AuthorizationDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -163,6 +201,20 @@ def __init__(self, version: Version, sid: str): DependentHostedNumberOrderList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthorizationDocumentInstance @@ -170,10 +222,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -182,55 +256,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AuthorizationDocumentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AuthorizationDocumentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = self._fetch() return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AuthorizationDocumentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthorizationDocumentInstance + Fetch the AuthorizationDocumentInstance and return response metadata - :returns: The fetched AuthorizationDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = await self._fetch_async() return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -261,6 +389,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance :param payload: Payload response from the API """ + return AuthorizationDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -285,7 +414,7 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/AuthorizationDocuments" - def create( + def _create( self, address_sid: str, email: str, @@ -293,18 +422,12 @@ def create( hosted_number_order_sids: List[str], contact_title: Union[str, object] = values.unset, cc_emails: Union[List[str], object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Create the AuthorizationDocumentInstance + Internal helper for create operation - :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. - :param email: Email that this AuthorizationDocument will be sent to for signing. - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. - :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. - - :returns: The created AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -325,13 +448,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AuthorizationDocumentInstance(self._version, payload) - - async def create_async( + def create( self, address_sid: str, email: str, @@ -341,7 +462,7 @@ async def create_async( cc_emails: Union[List[str], object] = values.unset, ) -> AuthorizationDocumentInstance: """ - Asynchronously create the AuthorizationDocumentInstance + Create the AuthorizationDocumentInstance :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. :param email: Email that this AuthorizationDocument will be sent to for signing. @@ -352,6 +473,63 @@ async def create_async( :returns: The created AuthorizationDocumentInstance """ + payload, _, _ = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -371,12 +549,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + payload, _, _ = await self._create_async( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) return AuthorizationDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AuthorizationDocumentInstance and return response metadata + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, email: Union[str, object] = values.unset, @@ -437,6 +676,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, email: Union[str, object] = values.unset, @@ -460,6 +759,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( email=email, @@ -492,6 +792,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -502,6 +803,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, email: Union[str, object] = values.unset, @@ -580,6 +943,88 @@ async def page_async( ) return AuthorizationDocumentPage(self._version, response) + def page_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AuthorizationDocumentPage: """ Retrieve a specific page of AuthorizationDocumentInstance records from the API. diff --git a/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py index 36f961f5ef..eed80d038f 100644 --- a/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py +++ b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -114,6 +115,7 @@ def get_instance( :param payload: Payload response from the API """ + return DependentHostedNumberOrderInstance( self._version, payload, @@ -231,6 +233,86 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union[ @@ -260,6 +342,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -300,6 +383,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -312,6 +396,84 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union[ @@ -357,7 +519,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -404,7 +568,111 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: """ @@ -416,7 +684,9 @@ def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: :returns: Page of DependentHostedNumberOrderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: """ @@ -428,7 +698,9 @@ async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPag :returns: Page of DependentHostedNumberOrderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/numbers/v2/bulk_hosted_number_order.py b/twilio/rest/numbers/v2/bulk_hosted_number_order.py index 7259c801d2..7ff4f50a40 100644 --- a/twilio/rest/numbers/v2/bulk_hosted_number_order.py +++ b/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( self._solution = { "bulk_hosting_sid": bulk_hosting_sid or self.bulk_hosting_sid, } + self._context: Optional[BulkHostedNumberOrderContext] = None @property @@ -114,6 +116,34 @@ async def fetch_async( order_status=order_status, ) + def fetch_with_http_info( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the BulkHostedNumberOrderInstance with HTTP info + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + order_status=order_status, + ) + + async def fetch_with_http_info_async( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance with HTTP info + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + order_status=order_status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,18 +173,15 @@ def __init__(self, version: Version, bulk_hosting_sid: str): **self._solution ) - def fetch( - self, order_status: Union[str, object] = values.unset - ) -> BulkHostedNumberOrderInstance: + def _fetch(self, order_status: Union[str, object] = values.unset) -> tuple: """ - Fetch the BulkHostedNumberOrderInstance - - :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + Internal helper for fetch operation - :returns: The fetched BulkHostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "OrderStatus": order_status, } @@ -164,28 +191,56 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + payload, _, _ = self._fetch(order_status=order_status) return BulkHostedNumberOrderInstance( self._version, payload, bulk_hosting_sid=self._solution["bulk_hosting_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, order_status: Union[str, object] = values.unset - ) -> BulkHostedNumberOrderInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + Fetch the BulkHostedNumberOrderInstance and return response metadata :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. - :returns: The fetched BulkHostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(order_status=order_status) + instance = BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "OrderStatus": order_status, } @@ -195,16 +250,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + payload, _, _ = await self._fetch_async(order_status=order_status) return BulkHostedNumberOrderInstance( self._version, payload, bulk_hosting_sid=self._solution["bulk_hosting_sid"], ) + async def fetch_with_http_info_async( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance and return response metadata + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + order_status=order_status + ) + instance = BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -228,15 +314,12 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/Orders/Bulk" - def create( - self, body: Union[object, object] = values.unset - ) -> BulkHostedNumberOrderInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the BulkHostedNumberOrderInstance + Internal helper for create operation - :param body: - - :returns: The created BulkHostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -246,22 +329,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return BulkHostedNumberOrderInstance(self._version, payload) - - async def create_async( + def create( self, body: Union[object, object] = values.unset ) -> BulkHostedNumberOrderInstance: """ - Asynchronously create the BulkHostedNumberOrderInstance + Create the BulkHostedNumberOrderInstance :param body: :returns: The created BulkHostedNumberOrderInstance """ + payload, _, _ = self._create(body=body) + return BulkHostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the BulkHostedNumberOrderInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = BulkHostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = body.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -270,12 +375,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronously create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + payload, _, _ = await self._create_async(body=body) return BulkHostedNumberOrderInstance(self._version, payload) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkHostedNumberOrderInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = BulkHostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: """ Constructs a BulkHostedNumberOrderContext diff --git a/twilio/rest/numbers/v2/bundle_clone.py b/twilio/rest/numbers/v2/bundle_clone.py index 820fbc9db5..7cee570fb3 100644 --- a/twilio/rest/numbers/v2/bundle_clone.py +++ b/twilio/rest/numbers/v2/bundle_clone.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( self._solution = { "bundle_sid": bundle_sid or self.bundle_sid, } + self._context: Optional[BundleCloneContext] = None @property @@ -133,6 +135,48 @@ async def create_async( friendly_name=friendly_name, ) + def create_with_http_info( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the BundleCloneInstance with HTTP info + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + async def create_with_http_info_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the BundleCloneInstance with HTTP info + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,6 +206,36 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) + def _create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, target_account_sid: str, @@ -177,6 +251,53 @@ def create( :returns: The created BundleCloneInstance """ + payload, _, _ = self._create( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the BundleCloneInstance and return response metadata + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + instance = BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "TargetAccountSid": target_account_sid, @@ -184,11 +305,14 @@ def create( "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BundleCloneInstance( - self._version, payload, bundle_sid=self._solution["bundle_sid"] + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) async def create_async( @@ -206,21 +330,39 @@ async def create_async( :returns: The created BundleCloneInstance """ - data = values.of( - { - "TargetAccountSid": target_account_sid, - "MoveToDraft": serialize.boolean_to_string(move_to_draft), - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, ) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - return BundleCloneInstance( + async def create_with_http_info_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the BundleCloneInstance and return response metadata + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target_account_sid=target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + instance = BundleCloneInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/numbers/v2/hosted_number_order.py b/twilio/rest/numbers/v2/hosted_number_order.py index 5ad2b6d920..dce5e77367 100644 --- a/twilio/rest/numbers/v2/hosted_number_order.py +++ b/twilio/rest/numbers/v2/hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,11 +26,13 @@ class HostedNumberOrderInstance(InstanceResource): class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" PENDING_LOA = "pending-loa" CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" COMPLETED = "completed" FAILED = "failed" ACTION_REQUIRED = "action-required" @@ -119,6 +122,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[HostedNumberOrderContext] = None @property @@ -154,6 +158,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "HostedNumberOrderInstance": """ Fetch the HostedNumberOrderInstance @@ -172,6 +194,24 @@ async def fetch_async(self) -> "HostedNumberOrderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "HostedNumberOrderInstance.Status", @@ -214,6 +254,48 @@ async def update_async( verification_call_extension=verification_call_extension, ) + def update_with_http_info( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance with HTTP info + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + async def update_with_http_info_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance with HTTP info + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -241,6 +323,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/HostedNumber/Orders/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the HostedNumberOrderInstance @@ -248,10 +344,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -260,69 +378,120 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> HostedNumberOrderInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the HostedNumberOrderInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched HostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = self._fetch() return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> HostedNumberOrderInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the HostedNumberOrderInstance + Fetch the HostedNumberOrderInstance and return response metadata - :returns: The fetched HostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = await self._fetch_async() return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: "HostedNumberOrderInstance.Status", verification_call_delay: Union[int, object] = values.unset, verification_call_extension: Union[str, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> tuple: """ - Update the HostedNumberOrderInstance + Internal helper for update operation - :param status: - :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. - :param verification_call_extension: The numerical extension to dial when making the ownership verification call. - - :returns: The updated HostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -338,28 +507,70 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + payload, _, _ = self._update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, status: "HostedNumberOrderInstance.Status", verification_call_delay: Union[int, object] = values.unset, verification_call_extension: Union[str, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the HostedNumberOrderInstance + Update the HostedNumberOrderInstance and return response metadata :param status: :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. :param verification_call_extension: The numerical extension to dial when making the ownership verification call. - :returns: The updated HostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -375,14 +586,59 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + payload, _, _ = await self._update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance and return response metadata + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -401,6 +657,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: :param payload: Payload response from the API """ + return HostedNumberOrderInstance(self._version, payload) def __repr__(self) -> str: @@ -425,7 +682,7 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/Orders" - def create( + def _create( self, phone_number: str, contact_phone_number: str, @@ -443,28 +700,12 @@ def create( status_callback_method: Union[str, object] = values.unset, sms_application_sid: Union[str, object] = values.unset, contact_title: Union[str, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> tuple: """ - Create the HostedNumberOrderInstance - - :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. - :param email: Optional. Email of the owner of this phone number that is being hosted. - :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. - :param friendly_name: A 128 character string that is a human readable text that describes this resource. - :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. - :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. - :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. - :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. - :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. - :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. - :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. - :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. - :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + Internal helper for create operation - :returns: The created HostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,13 +734,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return HostedNumberOrderInstance(self._version, payload) - - async def create_async( + def create( self, phone_number: str, contact_phone_number: str, @@ -519,7 +758,7 @@ async def create_async( contact_title: Union[str, object] = values.unset, ) -> HostedNumberOrderInstance: """ - Asynchronously create the HostedNumberOrderInstance + Create the HostedNumberOrderInstance :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. @@ -540,39 +779,267 @@ async def create_async( :returns: The created HostedNumberOrderInstance """ - - data = values.of( - { - "PhoneNumber": phone_number, - "ContactPhoneNumber": contact_phone_number, - "AddressSid": address_sid, - "Email": email, - "AccountSid": account_sid, - "FriendlyName": friendly_name, - "CcEmails": serialize.map(cc_emails, lambda e: e), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsCapability": serialize.boolean_to_string(sms_capability), - "SmsFallbackMethod": sms_fallback_method, - "StatusCallbackUrl": status_callback_url, - "StatusCallbackMethod": status_callback_method, - "SmsApplicationSid": sms_application_sid, - "ContactTitle": contact_title, - } + payload, _, _ = self._create( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" + return HostedNumberOrderInstance(self._version, payload) - payload = await self._version.create_async( + def create_with_http_info( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ContactPhoneNumber": contact_phone_number, + "AddressSid": address_sid, + "Email": email, + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "ContactTitle": contact_title, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) return HostedNumberOrderInstance(self._version, payload) + async def create_with_http_info_async( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + contact_phone_number=contact_phone_number, + address_sid=address_sid, + email=email, + account_sid=account_sid, + friendly_name=friendly_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_capability=sms_capability, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + contact_title=contact_title, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -657,6 +1124,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -686,6 +1235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -727,6 +1277,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -740,6 +1291,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -836,6 +1467,106 @@ async def page_async( ) return HostedNumberOrderPage(self._version, response) + def page_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> HostedNumberOrderPage: """ Retrieve a specific page of HostedNumberOrderInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py index 079540d87b..d917770b64 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,6 +99,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[BundleContext] = None @property @@ -133,6 +135,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BundleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BundleInstance": """ Fetch the BundleInstance @@ -151,6 +171,24 @@ async def fetch_async(self) -> "BundleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BundleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BundleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["BundleInstance.Status", object] = values.unset, @@ -199,6 +237,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the BundleInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BundleInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def bundle_copies(self) -> BundleCopyList: """ @@ -259,6 +345,20 @@ def __init__(self, version: Version, sid: str): self._item_assignments: Optional[ItemAssignmentList] = None self._replace_items: Optional[ReplaceItemsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BundleInstance @@ -266,10 +366,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BundleInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -278,71 +400,121 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BundleInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BundleInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BundleInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BundleInstance: + """ + Fetch the BundleInstance + + :returns: The fetched BundleInstance + """ + payload, _, _ = self._fetch() return BundleInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> BundleInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BundleInstance + Fetch the BundleInstance and return response metadata - :returns: The fetched BundleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BundleInstance: + """ + Asynchronous coroutine to fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + payload, _, _ = await self._fetch_async() return BundleInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BundleInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: Union["BundleInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> BundleInstance: + ) -> tuple: """ - Update the BundleInstance - - :param status: - :param status_callback: The URL we call to inform your application of status changes. - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Bundle resource changes status. + Internal helper for update operation - :returns: The updated BundleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -359,13 +531,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return BundleInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, status: Union["BundleInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, @@ -373,7 +543,7 @@ async def update_async( email: Union[str, object] = values.unset, ) -> BundleInstance: """ - Asynchronous coroutine to update the BundleInstance + Update the BundleInstance :param status: :param status_callback: The URL we call to inform your application of status changes. @@ -382,6 +552,53 @@ async def update_async( :returns: The updated BundleInstance """ + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the BundleInstance and return response metadata + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = BundleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -397,12 +614,61 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) return BundleInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BundleInstance and return response metadata + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = BundleInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def bundle_copies(self) -> BundleCopyList: """ @@ -469,6 +735,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: :param payload: Payload response from the API """ + return BundleInstance(self._version, payload) def __repr__(self) -> str: @@ -493,7 +760,7 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/Bundles" - def create( + def _create( self, friendly_name: str, email: str, @@ -503,20 +770,12 @@ def create( end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, number_type: Union[str, object] = values.unset, is_test: Union[bool, object] = values.unset, - ) -> BundleInstance: + ) -> tuple: """ - Create the BundleInstance - - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Bundle resource changes status. - :param status_callback: The URL we call to inform your application of status changes. - :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. - :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. - :param end_user_type: - :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. - :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + Internal helper for create operation - :returns: The created BundleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -537,13 +796,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return BundleInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -555,7 +812,7 @@ async def create_async( is_test: Union[bool, object] = values.unset, ) -> BundleInstance: """ - Asynchronously create the BundleInstance + Create the BundleInstance :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Bundle resource changes status. @@ -568,38 +825,180 @@ async def create_async( :returns: The created BundleInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "Email": email, - "StatusCallback": status_callback, - "RegulationSid": regulation_sid, - "IsoCountry": iso_country, - "EndUserType": end_user_type, - "NumberType": number_type, - "IsTest": serialize.boolean_to_string(is_test), - } + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" + return BundleInstance(self._version, payload) - headers["Accept"] = "application/json" + def create_with_http_info( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the BundleInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + instance = BundleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "StatusCallback": status_callback, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "EndUserType": end_user_type, + "NumberType": number_type, + "IsTest": serialize.boolean_to_string(is_test), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronously create the BundleInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: The created BundleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) return BundleInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BundleInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + status_callback=status_callback, + regulation_sid=regulation_sid, + iso_country=iso_country, + end_user_type=end_user_type, + number_type=number_type, + is_test=is_test, + ) + instance = BundleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -616,10 +1015,12 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -638,10 +1039,12 @@ def stream( limits = self._version.read_limits(limit, page_size) page = self.page( status=status, + bundle_sids=bundle_sids, friendly_name=friendly_name, regulation_sid=regulation_sid, iso_country=iso_country, number_type=number_type, + end_user_type=end_user_type, has_valid_until_date=has_valid_until_date, sort_by=sort_by, sort_direction=sort_direction, @@ -656,10 +1059,12 @@ def stream( async def stream_async( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -676,10 +1081,12 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -698,10 +1105,12 @@ async def stream_async( limits = self._version.read_limits(limit, page_size) page = await self.page_async( status=status, + bundle_sids=bundle_sids, friendly_name=friendly_name, regulation_sid=regulation_sid, iso_country=iso_country, number_type=number_type, + end_user_type=end_user_type, has_valid_until_date=has_valid_until_date, sort_by=sort_by, sort_direction=sort_direction, @@ -713,13 +1122,145 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BundleInstance and returns headers from first page + + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BundleInstance and returns headers from first page + + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -735,10 +1276,12 @@ def list( memory before returning. :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -754,13 +1297,16 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, + bundle_sids=bundle_sids, friendly_name=friendly_name, regulation_sid=regulation_sid, iso_country=iso_country, number_type=number_type, + end_user_type=end_user_type, has_valid_until_date=has_valid_until_date, sort_by=sort_by, sort_direction=sort_direction, @@ -775,10 +1321,12 @@ def list( async def list_async( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -794,10 +1342,12 @@ async def list_async( memory before returning. :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -813,14 +1363,17 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( status=status, + bundle_sids=bundle_sids, friendly_name=friendly_name, regulation_sid=regulation_sid, iso_country=iso_country, number_type=number_type, + end_user_type=end_user_type, has_valid_until_date=has_valid_until_date, sort_by=sort_by, sort_direction=sort_direction, @@ -832,13 +1385,143 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BundleInstance and returns headers from first page + + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BundleInstance and returns headers from first page + + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param str end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + bundle_sids=bundle_sids, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + end_user_type=end_user_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -854,10 +1537,12 @@ def page( Request is executed immediately :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -873,10 +1558,12 @@ def page( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, + "EndUserType": end_user_type, "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), "SortBy": sort_by, "SortDirection": sort_direction, @@ -901,10 +1588,12 @@ def page( async def page_async( self, status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, regulation_sid: Union[str, object] = values.unset, iso_country: Union[str, object] = values.unset, number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, has_valid_until_date: Union[bool, object] = values.unset, sort_by: Union["BundleInstance.SortBy", object] = values.unset, sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, @@ -920,10 +1609,12 @@ async def page_async( Request is executed immediately :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. @@ -939,10 +1630,12 @@ async def page_async( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, + "EndUserType": end_user_type, "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), "SortBy": sort_by, "SortDirection": sort_direction, @@ -964,6 +1657,154 @@ async def page_async( ) return BundlePage(self._version, response) + def page_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundlePage, status code, and headers + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BundlePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + bundle_sids: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + end_user_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param bundle_sids: A comma-separated list of Bundle SIDs to filter the results (maximum 20). Each Bundle SID must match `^BU[0-9a-fA-F]{32}$`. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param end_user_type: The end user type of the regulation of the Bundle. Can be `business` or `individual`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundlePage, status code, and headers + """ + data = values.of( + { + "Status": status, + "BundleSids": bundle_sids, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "EndUserType": end_user_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BundlePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> BundlePage: """ Retrieve a specific page of BundleInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py index d20a569690..d5f9d253c8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BundleCopyInstance: :param payload: Payload response from the API """ + return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -120,15 +122,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> BundleCopyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the BundleCopyInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the copied bundle. - - :returns: The created BundleCopyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -142,23 +141,49 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> BundleCopyInstance: + ) -> ApiResponse: """ - Asynchronously create the BundleCopyInstance + Create the BundleCopyInstance and return response metadata :param friendly_name: The string that you assigned to describe the copied bundle. - :returns: The created BundleCopyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -172,14 +197,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Asynchronously create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BundleCopyInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -230,6 +284,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -249,6 +353,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -275,6 +380,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -283,6 +389,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BundleCopyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -314,7 +470,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BundleCopyPage(self._version, response, self._solution) + return BundleCopyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -347,7 +503,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BundleCopyPage(self._version, response, self._solution) + return BundleCopyPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundleCopyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BundleCopyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BundleCopyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BundleCopyPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BundleCopyPage: """ @@ -359,7 +585,7 @@ def get_page(self, target_url: str) -> BundleCopyPage: :returns: Page of BundleCopyInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BundleCopyPage(self._version, response, self._solution) + return BundleCopyPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BundleCopyPage: """ @@ -371,7 +597,7 @@ async def get_page_async(self, target_url: str) -> BundleCopyPage: :returns: Page of BundleCopyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BundleCopyPage(self._version, response, self._solution) + return BundleCopyPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py index fd45064808..34107f1ca8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "bundle_sid": bundle_sid, "sid": sid or self.sid, } + self._context: Optional[EvaluationContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "EvaluationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -132,20 +152,30 @@ def __init__(self, version: Version, bundle_sid: str, sid: str): ) ) - def fetch(self) -> EvaluationInstance: + def _fetch(self) -> tuple: """ - Fetch the EvaluationInstance - + Internal helper for fetch operation - :returns: The fetched EvaluationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EvaluationInstance: + """ + Fetch the EvaluationInstance + + :returns: The fetched EvaluationInstance + """ + payload, _, _ = self._fetch() return EvaluationInstance( self._version, payload, @@ -153,22 +183,46 @@ def fetch(self) -> EvaluationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> EvaluationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EvaluationInstance + Fetch the EvaluationInstance and return response metadata - :returns: The fetched EvaluationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EvaluationInstance: + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + payload, _, _ = await self._fetch_async() return EvaluationInstance( self._version, payload, @@ -176,6 +230,22 @@ async def fetch_async(self) -> EvaluationInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: :param payload: Payload response from the API """ + return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -227,44 +298,88 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create(self) -> EvaluationInstance: + def _create(self) -> tuple: """ - Create the EvaluationInstance + Internal helper for create operation - - :returns: The created EvaluationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.create(method="POST", uri=self._uri, headers=headers) + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> EvaluationInstance: + """ + Create the EvaluationInstance + + :returns: The created EvaluationInstance + """ + payload, _, _ = self._create() return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - async def create_async(self) -> EvaluationInstance: + def create_with_http_info(self) -> ApiResponse: """ - Asynchronously create the EvaluationInstance + Create the EvaluationInstance and return response metadata - :returns: The created EvaluationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, headers=headers ) + async def create_async(self) -> EvaluationInstance: + """ + Asynchronously create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + payload, _, _ = await self._create_async() return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -315,6 +430,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -334,6 +499,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -360,6 +526,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -368,6 +535,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EvaluationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -399,7 +616,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EvaluationPage(self._version, response, self._solution) + return EvaluationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -432,7 +649,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EvaluationPage(self._version, response, self._solution) + return EvaluationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EvaluationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EvaluationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EvaluationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EvaluationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EvaluationPage: """ @@ -444,7 +731,7 @@ def get_page(self, target_url: str) -> EvaluationPage: :returns: Page of EvaluationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EvaluationPage(self._version, response, self._solution) + return EvaluationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EvaluationPage: """ @@ -456,7 +743,7 @@ async def get_page_async(self, target_url: str) -> EvaluationPage: :returns: Page of EvaluationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EvaluationPage(self._version, response, self._solution) + return EvaluationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> EvaluationContext: """ diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py index 4eb1fe2b33..336ee64979 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "bundle_sid": bundle_sid, "sid": sid or self.sid, } + self._context: Optional[ItemAssignmentContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ItemAssignmentInstance": """ Fetch the ItemAssignmentInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "ItemAssignmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, bundle_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ItemAssignmentInstance @@ -148,10 +200,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ItemAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -160,27 +234,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ItemAssignmentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ItemAssignmentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ItemAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ItemAssignmentInstance: + """ + Fetch the ItemAssignmentInstance + + :returns: The fetched ItemAssignmentInstance + """ + payload, _, _ = self._fetch() return ItemAssignmentInstance( self._version, payload, @@ -188,22 +278,46 @@ def fetch(self) -> ItemAssignmentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ItemAssignmentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ItemAssignmentInstance + Fetch the ItemAssignmentInstance and return response metadata - :returns: The fetched ItemAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ItemAssignmentInstance: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + payload, _, _ = await self._fetch_async() return ItemAssignmentInstance( self._version, payload, @@ -211,6 +325,22 @@ async def fetch_async(self) -> ItemAssignmentInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -229,6 +359,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: :param payload: Payload response from the API """ + return ItemAssignmentInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -262,13 +393,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create(self, object_sid: str) -> ItemAssignmentInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the ItemAssignmentInstance + Internal helper for create operation - :param object_sid: The SID of an object bag that holds information of the different items. - - :returns: The created ItemAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -282,21 +412,43 @@ def create(self, object_sid: str) -> ItemAssignmentInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, object_sid: str) -> ItemAssignmentInstance: + """ + Create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + payload, _, _ = self._create(object_sid=object_sid) return ItemAssignmentInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - async def create_async(self, object_sid: str) -> ItemAssignmentInstance: + def create_with_http_info(self, object_sid: str) -> ApiResponse: """ - Asynchronously create the ItemAssignmentInstance + Create the ItemAssignmentInstance and return response metadata :param object_sid: The SID of an object bag that holds information of the different items. - :returns: The created ItemAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,14 +462,37 @@ async def create_async(self, object_sid: str) -> ItemAssignmentInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, object_sid: str) -> ItemAssignmentInstance: + """ + Asynchronously create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + payload, _, _ = await self._create_async(object_sid=object_sid) return ItemAssignmentInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the ItemAssignmentInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -368,6 +543,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -387,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -413,6 +639,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -421,6 +648,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ItemAssignmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -452,7 +729,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ItemAssignmentPage(self._version, response, self._solution) + return ItemAssignmentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -485,7 +762,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ItemAssignmentPage(self._version, response, self._solution) + return ItemAssignmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ItemAssignmentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ItemAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ItemAssignmentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ItemAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ItemAssignmentPage: """ @@ -497,7 +844,7 @@ def get_page(self, target_url: str) -> ItemAssignmentPage: :returns: Page of ItemAssignmentInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ItemAssignmentPage(self._version, response, self._solution) + return ItemAssignmentPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ItemAssignmentPage: """ @@ -509,7 +856,7 @@ async def get_page_async(self, target_url: str) -> ItemAssignmentPage: :returns: Page of ItemAssignmentInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ItemAssignmentPage(self._version, response, self._solution) + return ItemAssignmentPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ItemAssignmentContext: """ diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py index a6a1de024d..cb9c9a46dd 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,13 +99,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: + def _create(self, from_bundle_sid: str) -> tuple: """ - Create the ReplaceItemsInstance + Internal helper for create operation - :param from_bundle_sid: The source bundle sid to copy the item assignments from. - - :returns: The created ReplaceItemsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -118,21 +118,43 @@ def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + payload, _, _ = self._create(from_bundle_sid=from_bundle_sid) return ReplaceItemsInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: + def create_with_http_info(self, from_bundle_sid: str) -> ApiResponse: """ - Asynchronously create the ReplaceItemsInstance + Create the ReplaceItemsInstance and return response metadata :param from_bundle_sid: The source bundle sid to copy the item assignments from. - :returns: The created ReplaceItemsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(from_bundle_sid=from_bundle_sid) + instance = ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, from_bundle_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -146,14 +168,39 @@ async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Asynchronously create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + payload, _, _ = await self._create_async(from_bundle_sid=from_bundle_sid) return ReplaceItemsInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async(self, from_bundle_sid: str) -> ApiResponse: + """ + Asynchronously create the ReplaceItemsInstance and return response metadata + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + from_bundle_sid=from_bundle_sid + ) + instance = ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py index ab1803372a..eaf2f958f2 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserContext] = None @property @@ -95,6 +97,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EndUserInstance": """ Fetch the EndUserInstance @@ -113,6 +133,24 @@ async def fetch_async(self) -> "EndUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -149,6 +187,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -176,6 +250,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EndUserInstance @@ -183,10 +271,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -195,67 +305,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> EndUserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the EndUserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + :returns: The fetched EndUserInstance + """ + payload, _, _ = self._fetch() return EndUserInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EndUserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EndUserInstance + Fetch the EndUserInstance and return response metadata - :returns: The fetched EndUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + payload, _, _ = await self._fetch_async() return EndUserInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Update the EndUserInstance - - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + Internal helper for update operation - :returns: The updated EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -270,25 +432,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronous coroutine to update the EndUserInstance + Update the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. :returns: The updated EndUserInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -302,12 +495,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -326,6 +554,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -350,20 +579,17 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/EndUsers" - def create( + def _create( self, friendly_name: str, type: "EndUserInstance.Type", attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Create the EndUserInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param type: - :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. - - :returns: The created EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -379,20 +605,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return EndUserInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: "EndUserInstance.Type", attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronously create the EndUserInstance + Create the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param type: @@ -400,6 +624,44 @@ async def create_async( :returns: The created EndUserInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -414,12 +676,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return EndUserInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -470,6 +771,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -489,6 +840,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -515,6 +867,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -523,6 +876,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -589,6 +992,76 @@ async def page_async( ) return EndUserPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EndUserPage: """ Retrieve a specific page of EndUserInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py index f14c8905c7..cf6534bbed 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "EndUserTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,48 +126,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/EndUserTypes/{sid}".format(**self._solution) - def fetch(self) -> EndUserTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the EndUserTypeInstance - + Internal helper for fetch operation - :returns: The fetched EndUserTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = self._fetch() return EndUserTypeInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EndUserTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EndUserTypeInstance + Fetch the EndUserTypeInstance and return response metadata - :returns: The fetched EndUserTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = await self._fetch_async() return EndUserTypeInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -240,6 +309,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -259,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -285,6 +405,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -293,6 +414,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -359,6 +530,76 @@ async def page_async( ) return EndUserTypePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EndUserTypePage: """ Retrieve a specific page of EndUserTypeInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py index 9c1227905e..88a84f8518 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RegulationContext] = None @property @@ -100,6 +102,34 @@ async def fetch_async( include_constraints=include_constraints, ) + def fetch_with_http_info( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RegulationInstance with HTTP info + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_constraints=include_constraints, + ) + + async def fetch_with_http_info_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RegulationInstance with HTTP info + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_constraints=include_constraints, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -127,18 +157,15 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) - def fetch( - self, include_constraints: Union[bool, object] = values.unset - ) -> RegulationInstance: + def _fetch(self, include_constraints: Union[bool, object] = values.unset) -> tuple: """ - Fetch the RegulationInstance + Internal helper for fetch operation - :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - - :returns: The fetched RegulationInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "IncludeConstraints": serialize.boolean_to_string(include_constraints), } @@ -148,28 +175,58 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + payload, _, _ = self._fetch(include_constraints=include_constraints) return RegulationInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async( + def fetch_with_http_info( self, include_constraints: Union[bool, object] = values.unset - ) -> RegulationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the RegulationInstance + Fetch the RegulationInstance and return response metadata :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields - :returns: The fetched RegulationInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + include_constraints=include_constraints + ) + instance = RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "IncludeConstraints": serialize.boolean_to_string(include_constraints), } @@ -179,16 +236,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Asynchronous coroutine to fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + payload, _, _ = await self._fetch_async(include_constraints=include_constraints) return RegulationInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RegulationInstance and return response metadata + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + include_constraints=include_constraints + ) + instance = RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +295,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: :param payload: Payload response from the API """ + return RegulationInstance(self._version, payload) def __repr__(self) -> str: @@ -309,6 +398,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, @@ -336,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_user_type=end_user_type, @@ -374,6 +540,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -386,6 +553,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, @@ -476,6 +717,100 @@ async def page_async( ) return RegulationPage(self._version, response) + def page_with_http_info( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RegulationPage, status code, and headers + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RegulationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RegulationPage, status code, and headers + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RegulationPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RegulationPage: """ Retrieve a specific page of RegulationInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py index b72f993858..abbddb13c1 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SupportingDocumentInstance": """ Fetch the SupportingDocumentInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "SupportingDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -163,6 +201,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -192,6 +266,20 @@ def __init__(self, version: Version, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SupportingDocumentInstance @@ -199,10 +287,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -211,67 +321,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SupportingDocumentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SupportingDocumentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = self._fetch() return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SupportingDocumentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SupportingDocumentInstance + Fetch the SupportingDocumentInstance and return response metadata - :returns: The fetched SupportingDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = await self._fetch_async() return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Update the SupportingDocumentInstance + Internal helper for update operation - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. - - :returns: The updated SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -286,26 +448,59 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SupportingDocumentInstance + Update the SupportingDocumentInstance and return response metadata :param friendly_name: The string that you assigned to describe the resource. :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. - :returns: The updated SupportingDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -320,14 +515,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -346,6 +578,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -370,20 +603,17 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/SupportingDocuments" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Create the SupportingDocumentInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param type: The type of the Supporting Document. - :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. - - :returns: The created SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -399,20 +629,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SupportingDocumentInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> SupportingDocumentInstance: """ - Asynchronously create the SupportingDocumentInstance + Create the SupportingDocumentInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of the Supporting Document. @@ -420,6 +648,44 @@ async def create_async( :returns: The created SupportingDocumentInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -434,12 +700,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return SupportingDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -490,6 +795,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -509,6 +864,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -535,6 +891,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -543,6 +900,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -609,6 +1016,76 @@ async def page_async( ) return SupportingDocumentPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SupportingDocumentPage: """ Retrieve a specific page of SupportingDocumentInstance records from the API. diff --git a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py index 692248cb45..d2de945f94 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "SupportingDocumentTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -108,48 +128,96 @@ def __init__(self, version: Version, sid: str): **self._solution ) - def fetch(self) -> SupportingDocumentTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the SupportingDocumentTypeInstance - + Internal helper for fetch operation - :returns: The fetched SupportingDocumentTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = self._fetch() return SupportingDocumentTypeInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SupportingDocumentTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + Fetch the SupportingDocumentTypeInstance and return response metadata - :returns: The fetched SupportingDocumentTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = await self._fetch_async() return SupportingDocumentTypeInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -168,6 +236,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstanc :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -242,6 +311,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -261,6 +380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -287,6 +407,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -295,6 +416,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -361,6 +532,76 @@ async def page_async( ) return SupportingDocumentTypePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SupportingDocumentTypePage: """ Retrieve a specific page of SupportingDocumentTypeInstance records from the API. diff --git a/twilio/rest/numbers/v3/__init__.py b/twilio/rest/numbers/v3/__init__.py new file mode 100644 index 0000000000..9826e176fb --- /dev/null +++ b/twilio/rest/numbers/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v3.hosted_number_order import HostedNumberOrderList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v3") + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V3>" diff --git a/twilio/rest/numbers/v3/hosted_number_order.py b/twilio/rest/numbers/v3/hosted_number_order.py new file mode 100644 index 0000000000..bce747ff13 --- /dev/null +++ b/twilio/rest/numbers/v3/hosted_number_order.py @@ -0,0 +1,529 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class HostedNumberOrderInstance(InstanceResource): + + class Status(object): + TWILIO_PROCESSING = "twilio-processing" + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 64 character string that is a human-readable text that describes this resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: A verification code provided in the response for a user to enter when they pick up the phone call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("accountSid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incomingPhoneNumberSid" + ) + self.address_sid: Optional[str] = payload.get("addressSid") + self.signing_document_sid: Optional[str] = payload.get("signingDocumentSid") + self.phone_number: Optional[str] = payload.get("phoneNumber") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.unique_name: Optional[str] = payload.get("uniqueName") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failureReason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verificationAttempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("ccEmails") + self.url: Optional[str] = payload.get("url") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verificationType") + self.verification_document_sid: Optional[str] = payload.get( + "verificationDocumentSid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("callDelay")) + self.verification_code: Optional[str] = payload.get("verificationCode") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verificationCallSids" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V3.HostedNumberOrderInstance>" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumbers/HostedNumberOrders" + + def _create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "phoneNumber": phone_number, + "smsCapability": serialize.boolean_to_string(sms_capability), + "accountSid": account_sid, + "friendlyName": friendly_name, + "uniqueName": unique_name, + "ccEmails": serialize.map(cc_emails, lambda e: e), + "smsUrl": sms_url, + "smsMethod": sms_method, + "smsFallbackUrl": sms_fallback_url, + "smsFallbackMethod": sms_fallback_method, + "statusCallbackUrl": status_callback_url, + "statusCallbackMethod": status_callback_method, + "smsApplicationSid": sms_application_sid, + "addressSid": address_sid, + "email": email, + "verificationType": verification_type, + "verificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "phoneNumber": phone_number, + "smsCapability": serialize.boolean_to_string(sms_capability), + "accountSid": account_sid, + "friendlyName": friendly_name, + "uniqueName": unique_name, + "ccEmails": serialize.map(cc_emails, lambda e: e), + "smsUrl": sms_url, + "smsMethod": sms_method, + "smsFallbackUrl": sms_fallback_url, + "smsFallbackMethod": sms_fallback_method, + "statusCallbackUrl": status_callback_url, + "statusCallbackMethod": status_callback_method, + "smsApplicationSid": sms_application_sid, + "addressSid": address_sid, + "email": email, + "verificationType": verification_type, + "verificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V3.HostedNumberOrderList>" diff --git a/twilio/rest/oauth/OauthBase.py b/twilio/rest/oauth/OauthBase.py index 87cbbac248..b26f459963 100644 --- a/twilio/rest/oauth/OauthBase.py +++ b/twilio/rest/oauth/OauthBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.oauth.v1 import V1 +from twilio.rest.oauth.v2 import V2 class OauthBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://oauth.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: @@ -36,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Oauth + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v1/authorize.py b/twilio/rest/oauth/v1/authorize.py index a353c4b8e0..69ff398da9 100644 --- a/twilio/rest/oauth/v1/authorize.py +++ b/twilio/rest/oauth/v1/authorize.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,19 +54,19 @@ def __init__(self, version: Version): self._uri = "/authorize" - def fetch( + def _fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, redirect_uri: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, state: Union[str, object] = values.unset, - ) -> AuthorizeInstance: + ) -> tuple: """ - Asynchronously fetch the AuthorizeInstance + Internal helper for fetch operation - :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback - :returns: The fetched AuthorizeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -81,13 +82,11 @@ def fetch( } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) - return AuthorizeInstance(self._version, payload) - - async def fetch_async( + def fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, @@ -96,11 +95,58 @@ async def fetch_async( state: Union[str, object] = values.unset, ) -> AuthorizeInstance: """ - Asynchronously fetch the AuthorizeInstance + Fetch the AuthorizeInstance :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback :returns: The fetched AuthorizeInstance """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" @@ -115,12 +161,57 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) return AuthorizeInstance(self._version, payload) + async def fetch_with_http_info_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v1/oauth_authorization_server.py b/twilio/rest/oauth/v1/oauth_authorization_server.py new file mode 100644 index 0000000000..4fcdd357c5 --- /dev/null +++ b/twilio/rest/oauth/v1/oauth_authorization_server.py @@ -0,0 +1,157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OauthAuthorizationServerInstance(InstanceResource): + """ + :ivar issuer: + :ivar authorization_endpoint: + :ivar token_endpoint: + :ivar response_types_supported: + :ivar grant_types_supported: + :ivar code_challenge_methods_supported: + :ivar token_endpoint_auth_methods_supported: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.issuer: Optional[str] = payload.get("issuer") + self.authorization_endpoint: Optional[str] = payload.get( + "authorization_endpoint" + ) + self.token_endpoint: Optional[str] = payload.get("token_endpoint") + self.response_types_supported: Optional[ + "OauthAuthorizationServerInstance.str]" + ] = payload.get("response_types_supported") + self.grant_types_supported: Optional[ + "OauthAuthorizationServerInstance.str]" + ] = payload.get("grant_types_supported") + self.code_challenge_methods_supported: Optional[ + "OauthAuthorizationServerInstance.str]" + ] = payload.get("code_challenge_methods_supported") + self.token_endpoint_auth_methods_supported: Optional[ + "OauthAuthorizationServerInstance.str]" + ] = payload.get("token_endpoint_auth_methods_supported") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Oauth.V1.OauthAuthorizationServerInstance>" + + +class OauthAuthorizationServerList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OauthAuthorizationServerList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/oauth-authorization-server" + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> OauthAuthorizationServerInstance: + """ + Fetch the OauthAuthorizationServerInstance + + + :returns: The fetched OauthAuthorizationServerInstance + """ + payload, _, _ = self._fetch() + return OauthAuthorizationServerInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OauthAuthorizationServerInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OauthAuthorizationServerInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> OauthAuthorizationServerInstance: + """ + Asynchronously fetch the OauthAuthorizationServerInstance + + + :returns: The fetched OauthAuthorizationServerInstance + """ + payload, _, _ = await self._fetch_async() + return OauthAuthorizationServerInstance(self._version, payload) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the OauthAuthorizationServerInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OauthAuthorizationServerInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V1.OauthAuthorizationServerList>" diff --git a/twilio/rest/oauth/v1/token.py b/twilio/rest/oauth/v1/token.py index 18de1008cb..ebf53dc523 100644 --- a/twilio/rest/oauth/v1/token.py +++ b/twilio/rest/oauth/v1/token.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,7 +62,7 @@ def __init__(self, version: Version): self._uri = "/token" - def create( + def _create( self, grant_type: str, client_id: str, @@ -71,20 +72,12 @@ def create( audience: Union[str, object] = values.unset, refresh_token: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, - ) -> TokenInstance: + ) -> tuple: """ - Create the TokenInstance - - :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. - :param client_id: A 34 character string that uniquely identifies this OAuth App. - :param client_secret: The credential for confidential OAuth App. - :param code: JWT token related to the authorization code grant type. - :param redirect_uri: The redirect uri - :param audience: The targeted audience uri - :param refresh_token: JWT token related to refresh access token. - :param scope: The scope of token + Internal helper for create operation - :returns: The created TokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -105,13 +98,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TokenInstance(self._version, payload) - - async def create_async( + def create( self, grant_type: str, client_id: str, @@ -123,7 +114,7 @@ async def create_async( scope: Union[str, object] = values.unset, ) -> TokenInstance: """ - Asynchronously create the TokenInstance + Create the TokenInstance :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. :param client_id: A 34 character string that uniquely identifies this OAuth App. @@ -136,6 +127,73 @@ async def create_async( :returns: The created TokenInstance """ + payload, _, _ = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -155,12 +213,85 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) return TokenInstance(self._version, payload) + async def create_with_http_info_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v2/__init__.py b/twilio/rest/oauth/v2/__init__.py new file mode 100644 index 0000000000..c061f851c4 --- /dev/null +++ b/twilio/rest/oauth/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.oauth.v2.authorize import AuthorizeList +from twilio.rest.oauth.v2.token import TokenList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Oauth + + :param domain: The Twilio.oauth domain + """ + super().__init__(domain, "v2") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V2>" diff --git a/twilio/rest/oauth/v2/authorize.py b/twilio/rest/oauth/v2/authorize.py new file mode 100644 index 0000000000..717b31b5aa --- /dev/null +++ b/twilio/rest/oauth/v2/authorize.py @@ -0,0 +1,245 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Oauth.V2.AuthorizeInstance>" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def _fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + "code_challenge": code_challenge, + "code_challenge_method": code_challenge_method, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Fetch the AuthorizeInstance + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: :param code_challenge: :param code_challenge_method: + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: :param code_challenge: :param code_challenge_method: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + "code_challenge": code_challenge, + "code_challenge_method": code_challenge_method, + } + ) + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: :param code_challenge: :param code_challenge_method: + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + ) + return AuthorizeInstance(self._version, payload) + + async def fetch_with_http_info_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + code_challenge: Union[str, object] = values.unset, + code_challenge_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: :param code_challenge: :param code_challenge_method: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + code_challenge=code_challenge, + code_challenge_method=code_challenge_method, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V2.AuthorizeList>" diff --git a/twilio/rest/oauth/v2/token.py b/twilio/rest/oauth/v2/token.py new file mode 100644 index 0000000000..07bff732c5 --- /dev/null +++ b/twilio/rest/oauth/v2/token.py @@ -0,0 +1,343 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Oauth.V2.TokenInstance>" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def _create( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + "code_verifier": code_verifier, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + params = values.of( + { + "account_sid": account_sid, + } + ) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + def create( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param account_sid: Optional Account SID to perform on behalf of requests. + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + :param code_verifier: The PKCE code verifier used to generate the code_challenge in the authorization request. + + :returns: The created TokenInstance + """ + payload, _, _ = self._create( + account_sid=account_sid, + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + code_verifier=code_verifier, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param account_sid: Optional Account SID to perform on behalf of requests. + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + :param code_verifier: The PKCE code verifier used to generate the code_challenge in the authorization request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + account_sid=account_sid, + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + code_verifier=code_verifier, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + "code_verifier": code_verifier, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + params = values.of( + { + "account_sid": account_sid, + } + ) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers, params=params + ) + + async def create_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param account_sid: Optional Account SID to perform on behalf of requests. + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + :param code_verifier: The PKCE code verifier used to generate the code_challenge in the authorization request. + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async( + account_sid=account_sid, + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + code_verifier=code_verifier, + ) + return TokenInstance(self._version, payload) + + async def create_with_http_info_async( + self, + account_sid: Union[str, object] = values.unset, + grant_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + code_verifier: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param account_sid: Optional Account SID to perform on behalf of requests. + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + :param code_verifier: The PKCE code verifier used to generate the code_challenge in the authorization request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + account_sid=account_sid, + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + code_verifier=code_verifier, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V2.TokenList>" diff --git a/twilio/rest/preview/PreviewBase.py b/twilio/rest/preview/PreviewBase.py index 2b44efaf63..dd8317b4c0 100644 --- a/twilio/rest/preview/PreviewBase.py +++ b/twilio/rest/preview/PreviewBase.py @@ -14,7 +14,6 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.preview.hosted_numbers import HostedNumbers -from twilio.rest.preview.sync import Sync from twilio.rest.preview.marketplace import Marketplace from twilio.rest.preview.wireless import Wireless @@ -29,7 +28,6 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://preview.twilio.com") self._hosted_numbers: Optional[HostedNumbers] = None - self._sync: Optional[Sync] = None self._marketplace: Optional[Marketplace] = None self._wireless: Optional[Wireless] = None @@ -42,15 +40,6 @@ def hosted_numbers(self) -> HostedNumbers: self._hosted_numbers = HostedNumbers(self) return self._hosted_numbers - @property - def sync(self) -> Sync: - """ - :returns: Versions sync of Preview - """ - if self._sync is None: - self._sync = Sync(self) - return self._sync - @property def marketplace(self) -> Marketplace: """ diff --git a/twilio/rest/preview/__init__.py b/twilio/rest/preview/__init__.py index 501ae417d0..c4658c62e3 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -7,7 +7,6 @@ from twilio.rest.preview.hosted_numbers.hosted_number_order import HostedNumberOrderList from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList -from twilio.rest.preview.sync.service import ServiceList from twilio.rest.preview.wireless.command import CommandList from twilio.rest.preview.wireless.rate_plan import RatePlanList from twilio.rest.preview.wireless.sim import SimList @@ -51,15 +50,6 @@ def installed_add_ons(self) -> InstalledAddOnList: ) return self.marketplace.installed_add_ons - @property - def services(self) -> ServiceList: - warn( - "services is deprecated. Use sync.services instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.sync.services - @property def commands(self) -> CommandList: warn( diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py index 49d3d40da5..27ff55c37d 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AuthorizationDocumentContext] = None @property @@ -105,6 +107,24 @@ async def fetch_async(self) -> "AuthorizationDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, hosted_number_order_sids: Union[List[str], object] = values.unset, @@ -171,6 +191,72 @@ async def update_async( contact_phone_number=contact_phone_number, ) + def update_with_http_info( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AuthorizationDocumentInstance with HTTP info + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + async def update_with_http_info_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance with HTTP info + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -211,49 +297,97 @@ def __init__(self, version: Version, sid: str): DependentHostedNumberOrderList ] = None - def fetch(self) -> AuthorizationDocumentInstance: + def _fetch(self) -> tuple: """ - Fetch the AuthorizationDocumentInstance - + Internal helper for fetch operation - :returns: The fetched AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = self._fetch() return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AuthorizationDocumentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AuthorizationDocumentInstance + Fetch the AuthorizationDocumentInstance and return response metadata - :returns: The fetched AuthorizationDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = await self._fetch_async() return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, hosted_number_order_sids: Union[List[str], object] = values.unset, address_sid: Union[str, object] = values.unset, @@ -262,19 +396,12 @@ def update( status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, contact_title: Union[str, object] = values.unset, contact_phone_number: Union[str, object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Update the AuthorizationDocumentInstance - - :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. - :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. - :param email: Email that this AuthorizationDocument will be sent to for signing. - :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed - :param status: - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + Internal helper for update operation - :returns: The updated AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,15 +423,47 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + payload, _, _ = self._update( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, hosted_number_order_sids: Union[List[str], object] = values.unset, address_sid: Union[str, object] = values.unset, @@ -313,9 +472,9 @@ async def update_async( status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, contact_title: Union[str, object] = values.unset, contact_phone_number: Union[str, object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AuthorizationDocumentInstance + Update the AuthorizationDocumentInstance and return response metadata :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. @@ -325,7 +484,37 @@ async def update_async( :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :returns: The updated AuthorizationDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + instance = AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -347,14 +536,83 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + payload, _, _ = await self._update_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) return AuthorizationDocumentInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance and return response metadata + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + instance = AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -387,6 +645,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance :param payload: Payload response from the API """ + return AuthorizationDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -411,7 +670,7 @@ def __init__(self, version: Version): self._uri = "/AuthorizationDocuments" - def create( + def _create( self, hosted_number_order_sids: List[str], address_sid: str, @@ -419,18 +678,12 @@ def create( contact_title: str, contact_phone_number: str, cc_emails: Union[List[str], object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Create the AuthorizationDocumentInstance - - :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. - :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. - :param email: Email that this AuthorizationDocument will be sent to for signing. - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + Internal helper for create operation - :returns: The created AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -451,13 +704,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AuthorizationDocumentInstance(self._version, payload) - - async def create_async( + def create( self, hosted_number_order_sids: List[str], address_sid: str, @@ -467,7 +718,7 @@ async def create_async( cc_emails: Union[List[str], object] = values.unset, ) -> AuthorizationDocumentInstance: """ - Asynchronously create the AuthorizationDocumentInstance + Create the AuthorizationDocumentInstance :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. @@ -478,6 +729,63 @@ async def create_async( :returns: The created AuthorizationDocumentInstance """ + payload, _, _ = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -497,12 +805,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + payload, _, _ = await self._create_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) return AuthorizationDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AuthorizationDocumentInstance and return response metadata + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, email: Union[str, object] = values.unset, @@ -563,6 +932,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, email: Union[str, object] = values.unset, @@ -586,6 +1015,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( email=email, @@ -618,6 +1048,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -628,6 +1059,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, email: Union[str, object] = values.unset, @@ -706,6 +1199,88 @@ async def page_async( ) return AuthorizationDocumentPage(self._version, response) + def page_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizationDocumentPage, status code, and headers + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizationDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AuthorizationDocumentPage: """ Retrieve a specific page of AuthorizationDocumentInstance records from the API. diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py b/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py index 0ec58f8792..1d52db3b65 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,7 @@ class DependentHostedNumberOrderInstance(InstanceResource): class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -134,6 +136,7 @@ def get_instance( :param payload: Payload response from the API """ + return DependentHostedNumberOrderInstance( self._version, payload, @@ -257,6 +260,92 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union[ @@ -288,6 +377,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -331,6 +421,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -344,6 +435,90 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union[ @@ -392,7 +567,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -442,7 +619,117 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentHostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: """ @@ -454,7 +741,9 @@ def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: :returns: Page of DependentHostedNumberOrderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: """ @@ -466,7 +755,9 @@ async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPag :returns: Page of DependentHostedNumberOrderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/preview/hosted_numbers/hosted_number_order.py b/twilio/rest/preview/hosted_numbers/hosted_number_order.py index 0c20af8791..1b26c1b53b 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,7 @@ class HostedNumberOrderInstance(InstanceResource): class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -113,6 +115,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[HostedNumberOrderContext] = None @property @@ -148,6 +151,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "HostedNumberOrderInstance": """ Fetch the HostedNumberOrderInstance @@ -166,6 +187,24 @@ async def fetch_async(self) -> "HostedNumberOrderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -254,6 +293,94 @@ async def update_async( call_delay=call_delay, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance with HTTP info + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance with HTTP info + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -283,6 +410,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the HostedNumberOrderInstance @@ -290,10 +431,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -302,56 +465,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> HostedNumberOrderInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the HostedNumberOrderInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched HostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = self._fetch() return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> HostedNumberOrderInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the HostedNumberOrderInstance + Fetch the HostedNumberOrderInstance and return response metadata - :returns: The fetched HostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = await self._fetch_async() return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, @@ -365,22 +582,12 @@ def update( verification_document_sid: Union[str, object] = values.unset, extension: Union[str, object] = values.unset, call_delay: Union[int, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> tuple: """ - Update the HostedNumberOrderInstance - - :param friendly_name: A 64 character string that is a human readable text that describes this resource. - :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. - :param email: Email of the owner of this phone number that is being hosted. - :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. - :param status: - :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. - :param verification_type: - :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. - :param extension: Digits to dial after connecting the verification call. - :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + Internal helper for update operation - :returns: The updated HostedNumberOrderInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -403,15 +610,58 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) return HostedNumberOrderInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, @@ -425,9 +675,9 @@ async def update_async( verification_document_sid: Union[str, object] = values.unset, extension: Union[str, object] = values.unset, call_delay: Union[int, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the HostedNumberOrderInstance + Update the HostedNumberOrderInstance and return response metadata :param friendly_name: A 64 character string that is a human readable text that describes this resource. :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. @@ -440,7 +690,45 @@ async def update_async( :param extension: Digits to dial after connecting the verification call. :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. - :returns: The updated HostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -463,14 +751,105 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return HostedNumberOrderInstance( - self._version, payload, sid=self._solution["sid"] + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance and return response metadata + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + instance = HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -491,6 +870,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: :param payload: Payload response from the API """ + return HostedNumberOrderInstance(self._version, payload) def __repr__(self) -> str: @@ -515,6 +895,66 @@ def __init__(self, version: Version): self._uri = "/HostedNumberOrders" + def _create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, phone_number: str, @@ -560,6 +1000,122 @@ def create( :returns: The created HostedNumberOrderInstance """ + payload, _, _ = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -588,12 +1144,10 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return HostedNumberOrderInstance(self._version, payload) - async def create_async( self, phone_number: str, @@ -617,7 +1171,73 @@ async def create_async( verification_document_sid: Union[str, object] = values.unset, ) -> HostedNumberOrderInstance: """ - Asynchronously create the HostedNumberOrderInstance + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. @@ -637,41 +1257,29 @@ async def create_async( :param verification_type: :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. - :returns: The created HostedNumberOrderInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "PhoneNumber": phone_number, - "SmsCapability": serialize.boolean_to_string(sms_capability), - "AccountSid": account_sid, - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "CcEmails": serialize.map(cc_emails, lambda e: e), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsFallbackMethod": sms_fallback_method, - "StatusCallbackUrl": status_callback_url, - "StatusCallbackMethod": status_callback_method, - "SmsApplicationSid": sms_application_sid, - "AddressSid": address_sid, - "Email": email, - "VerificationType": verification_type, - "VerificationDocumentSid": verification_document_sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, ) - - return HostedNumberOrderInstance(self._version, payload) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -757,6 +1365,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -786,6 +1476,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -827,6 +1518,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -840,6 +1532,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -936,6 +1708,106 @@ async def page_async( ) return HostedNumberOrderPage(self._version, response) + def page_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HostedNumberOrderPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HostedNumberOrderPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> HostedNumberOrderPage: """ Retrieve a specific page of HostedNumberOrderInstance records from the API. diff --git a/twilio/rest/preview/marketplace/available_add_on/__init__.py b/twilio/rest/preview/marketplace/available_add_on/__init__.py index e81ec649de..76fc06a367 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "AvailableAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -124,48 +144,96 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[AvailableAddOnExtensionList] = None - def fetch(self) -> AvailableAddOnInstance: + def _fetch(self) -> tuple: """ - Fetch the AvailableAddOnInstance - + Internal helper for fetch operation - :returns: The fetched AvailableAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = self._fetch() return AvailableAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> AvailableAddOnInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AvailableAddOnInstance + Fetch the AvailableAddOnInstance and return response metadata - :returns: The fetched AvailableAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = await self._fetch_async() return AvailableAddOnInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -196,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: :param payload: Payload response from the API """ + return AvailableAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -270,6 +339,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -289,6 +408,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -315,6 +435,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -323,6 +444,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -389,6 +560,76 @@ async def page_async( ) return AvailableAddOnPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AvailableAddOnPage: """ Retrieve a specific page of AvailableAddOnInstance records from the API. diff --git a/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py b/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py index 4c05f4244d..1d680e91c1 100644 --- a/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py +++ b/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "available_add_on_sid": available_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnExtensionContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "AvailableAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -120,20 +140,30 @@ def __init__(self, version: Version, available_add_on_sid: str, sid: str): **self._solution ) - def fetch(self) -> AvailableAddOnExtensionInstance: + def _fetch(self) -> tuple: """ - Fetch the AvailableAddOnExtensionInstance - + Internal helper for fetch operation - :returns: The fetched AvailableAddOnExtensionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = self._fetch() return AvailableAddOnExtensionInstance( self._version, payload, @@ -141,22 +171,46 @@ def fetch(self) -> AvailableAddOnExtensionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AvailableAddOnExtensionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + Fetch the AvailableAddOnExtensionInstance and return response metadata - :returns: The fetched AvailableAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() return AvailableAddOnExtensionInstance( self._version, payload, @@ -164,6 +218,22 @@ async def fetch_async(self) -> AvailableAddOnExtensionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -184,6 +254,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstan :param payload: Payload response from the API """ + return AvailableAddOnExtensionInstance( self._version, payload, @@ -269,6 +340,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -288,6 +409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -314,6 +436,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -322,6 +445,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AvailableAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -353,7 +526,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -386,7 +561,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailableAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: """ @@ -398,7 +649,9 @@ def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: :returns: Page of AvailableAddOnExtensionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: """ @@ -410,7 +663,9 @@ async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: :returns: Page of AvailableAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> AvailableAddOnExtensionContext: """ diff --git a/twilio/rest/preview/marketplace/installed_add_on/__init__.py b/twilio/rest/preview/marketplace/installed_add_on/__init__.py index 7f1fadc510..c7352ed699 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InstalledAddOnInstance": """ Fetch the InstalledAddOnInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "InstalledAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration: Union[object, object] = values.unset, @@ -151,6 +189,42 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration=configuration, + unique_name=unique_name, + ) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -187,6 +261,20 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[InstalledAddOnExtensionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InstalledAddOnInstance @@ -194,10 +282,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -206,67 +316,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InstalledAddOnInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InstalledAddOnInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = self._fetch() return InstalledAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> InstalledAddOnInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InstalledAddOnInstance + Fetch the InstalledAddOnInstance and return response metadata - :returns: The fetched InstalledAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = await self._fetch_async() return InstalledAddOnInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Update the InstalledAddOnInstance - - :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + Internal helper for update operation - :returns: The updated InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,25 +443,60 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronous coroutine to update the InstalledAddOnInstance + Update the InstalledAddOnInstance :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. :returns: The updated InstalledAddOnInstance """ + payload, _, _ = self._update( + configuration=configuration, unique_name=unique_name + ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance and return response metadata + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -313,12 +510,49 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + payload, _, _ = await self._update_async( + configuration=configuration, unique_name=unique_name + ) return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance and return response metadata + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + configuration=configuration, unique_name=unique_name + ) + instance = InstalledAddOnInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -349,6 +583,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: :param payload: Payload response from the API """ + return InstalledAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -373,22 +608,18 @@ def __init__(self, version: Version): self._uri = "/InstalledAddOns" - def create( + def _create( self, available_add_on_sid: str, accept_terms_of_service: bool, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Create the InstalledAddOnInstance + Internal helper for create operation - :param available_add_on_sid: The SID of the AvaliableAddOn to install. - :param accept_terms_of_service: Whether the Terms of Service were accepted. - :param configuration: The JSON object that represents the configuration of the new Add-on being installed. - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. - - :returns: The created InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -407,13 +638,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return InstalledAddOnInstance(self._version, payload) - - async def create_async( + def create( self, available_add_on_sid: str, accept_terms_of_service: bool, @@ -421,7 +650,7 @@ async def create_async( unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronously create the InstalledAddOnInstance + Create the InstalledAddOnInstance :param available_add_on_sid: The SID of the AvaliableAddOn to install. :param accept_terms_of_service: Whether the Terms of Service were accepted. @@ -430,6 +659,53 @@ async def create_async( :returns: The created InstalledAddOnInstance """ + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -447,12 +723,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + payload, _, _ = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) return InstalledAddOnInstance(self._version, payload) + async def create_with_http_info_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -503,6 +828,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -522,6 +897,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -548,6 +924,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -556,6 +933,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -622,6 +1049,76 @@ async def page_async( ) return InstalledAddOnPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InstalledAddOnPage: """ Retrieve a specific page of InstalledAddOnInstance records from the API. diff --git a/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py b/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py index e0574ee2fd..0c7f88938d 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py +++ b/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "installed_add_on_sid": installed_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnExtensionContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "InstalledAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": """ Update the InstalledAddOnExtensionInstance @@ -113,6 +133,30 @@ async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance" enabled=enabled, ) + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,20 +190,30 @@ def __init__(self, version: Version, installed_add_on_sid: str, sid: str): **self._solution ) - def fetch(self) -> InstalledAddOnExtensionInstance: + def _fetch(self) -> tuple: """ - Fetch the InstalledAddOnExtensionInstance - + Internal helper for fetch operation - :returns: The fetched InstalledAddOnExtensionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = self._fetch() return InstalledAddOnExtensionInstance( self._version, payload, @@ -167,22 +221,46 @@ def fetch(self) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InstalledAddOnExtensionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + Fetch the InstalledAddOnExtensionInstance and return response metadata - :returns: The fetched InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = await self._fetch_async() return InstalledAddOnExtensionInstance( self._version, payload, @@ -190,13 +268,28 @@ async def fetch_async(self) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the InstalledAddOnExtensionInstance + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance and return response metadata - :param enabled: Whether the Extension should be invoked. - :returns: The updated InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, enabled: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -210,10 +303,19 @@ def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + payload, _, _ = self._update(enabled=enabled) return InstalledAddOnExtensionInstance( self._version, payload, @@ -221,13 +323,29 @@ def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) - async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + def update_with_http_info(self, enabled: bool) -> ApiResponse: """ - Asynchronous coroutine to update the InstalledAddOnExtensionInstance + Update the InstalledAddOnExtensionInstance and return response metadata :param enabled: Whether the Extension should be invoked. - :returns: The updated InstalledAddOnExtensionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, enabled: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -241,10 +359,19 @@ async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + payload, _, _ = await self._update_async(enabled=enabled) return InstalledAddOnExtensionInstance( self._version, payload, @@ -252,6 +379,23 @@ async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance and return response metadata + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(enabled=enabled) + instance = InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -272,6 +416,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstan :param payload: Payload response from the API """ + return InstalledAddOnExtensionInstance( self._version, payload, @@ -357,6 +502,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -376,6 +571,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -402,6 +598,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -410,6 +607,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnExtensionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -441,7 +688,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -474,7 +723,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InstalledAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: """ @@ -486,7 +811,9 @@ def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: :returns: Page of InstalledAddOnExtensionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: """ @@ -498,7 +825,9 @@ async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: :returns: Page of InstalledAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> InstalledAddOnExtensionContext: """ diff --git a/twilio/rest/preview/sync/service/__init__.py b/twilio/rest/preview/sync/service/__init__.py deleted file mode 100644 index 7b09429375..0000000000 --- a/twilio/rest/preview/sync/service/__init__.py +++ /dev/null @@ -1,741 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.preview.sync.service.document import DocumentList -from twilio.rest.preview.sync.service.sync_list import SyncListList -from twilio.rest.preview.sync.service.sync_map import SyncMapList - - -class ServiceInstance(InstanceResource): - """ - :ivar sid: - :ivar account_sid: - :ivar friendly_name: - :ivar date_created: - :ivar date_updated: - :ivar url: - :ivar webhook_url: - :ivar reachability_webhooks_enabled: - :ivar acl_enabled: - :ivar links: - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - self.webhook_url: Optional[str] = payload.get("webhook_url") - self.reachability_webhooks_enabled: Optional[bool] = payload.get( - "reachability_webhooks_enabled" - ) - self.acl_enabled: Optional[bool] = payload.get("acl_enabled") - self.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[ServiceContext] = None - - @property - def _proxy(self) -> "ServiceContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ServiceContext for this ServiceInstance - """ - if self._context is None: - self._context = ServiceContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ServiceInstance": - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ServiceInstance": - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> "ServiceInstance": - """ - Update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - return self._proxy.update( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, - ) - - async def update_async( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> "ServiceInstance": - """ - Asynchronous coroutine to update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - return await self._proxy.update_async( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, - ) - - @property - def documents(self) -> DocumentList: - """ - Access the documents - """ - return self._proxy.documents - - @property - def sync_lists(self) -> SyncListList: - """ - Access the sync_lists - """ - return self._proxy.sync_lists - - @property - def sync_maps(self) -> SyncMapList: - """ - Access the sync_maps - """ - return self._proxy.sync_maps - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.ServiceInstance {}>".format(context) - - -class ServiceContext(InstanceContext): - - def __init__(self, version: Version, sid: str): - """ - Initialize the ServiceContext - - :param version: Version that contains the resource - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Services/{sid}".format(**self._solution) - - self._documents: Optional[DocumentList] = None - self._sync_lists: Optional[SyncListList] = None - self._sync_maps: Optional[SyncMapList] = None - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ServiceInstance: - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ServiceInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: - """ - Update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - - data = values.of( - { - "WebhookUrl": webhook_url, - "FriendlyName": friendly_name, - "ReachabilityWebhooksEnabled": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: - """ - Asynchronous coroutine to update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - - data = values.of( - { - "WebhookUrl": webhook_url, - "FriendlyName": friendly_name, - "ReachabilityWebhooksEnabled": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def documents(self) -> DocumentList: - """ - Access the documents - """ - if self._documents is None: - self._documents = DocumentList( - self._version, - self._solution["sid"], - ) - return self._documents - - @property - def sync_lists(self) -> SyncListList: - """ - Access the sync_lists - """ - if self._sync_lists is None: - self._sync_lists = SyncListList( - self._version, - self._solution["sid"], - ) - return self._sync_lists - - @property - def sync_maps(self) -> SyncMapList: - """ - Access the sync_maps - """ - if self._sync_maps is None: - self._sync_maps = SyncMapList( - self._version, - self._solution["sid"], - ) - return self._sync_maps - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.ServiceContext {}>".format(context) - - -class ServicePage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: - """ - Build an instance of ServiceInstance - - :param payload: Payload response from the API - """ - return ServiceInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.ServicePage>" - - -class ServiceList(ListResource): - - def __init__(self, version: Version): - """ - Initialize the ServiceList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Services" - - def create( - self, - friendly_name: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: - """ - Create the ServiceInstance - - :param friendly_name: - :param webhook_url: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The created ServiceInstance - """ - - data = values.of( - { - "FriendlyName": friendly_name, - "WebhookUrl": webhook_url, - "ReachabilityWebhooksEnabled": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: - """ - Asynchronously create the ServiceInstance - - :param friendly_name: - :param webhook_url: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The created ServiceInstance - """ - - data = values.of( - { - "FriendlyName": friendly_name, - "WebhookUrl": webhook_url, - "ReachabilityWebhooksEnabled": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ServiceInstance]: - """ - Streams ServiceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[ServiceInstance]: - """ - Asynchronously streams ServiceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ServiceInstance]: - """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ServiceInstance]: - """ - Asynchronously lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ServicePage: - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ServicePage(self._version, response) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ServicePage: - """ - Asynchronously retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ServicePage(self._version, response) - - def get_page(self, target_url: str) -> ServicePage: - """ - Retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return ServicePage(self._version, response) - - async def get_page_async(self, target_url: str) -> ServicePage: - """ - Asynchronously retrieve a specific page of ServiceInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ServiceInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return ServicePage(self._version, response) - - def get(self, sid: str) -> ServiceContext: - """ - Constructs a ServiceContext - - :param sid: - """ - return ServiceContext(self._version, sid=sid) - - def __call__(self, sid: str) -> ServiceContext: - """ - Constructs a ServiceContext - - :param sid: - """ - return ServiceContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.ServiceList>" diff --git a/twilio/rest/preview/sync/service/document/__init__.py b/twilio/rest/preview/sync/service/document/__init__.py deleted file mode 100644 index ee55186ca4..0000000000 --- a/twilio/rest/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,693 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.preview.sync.service.document.document_permission import ( - DocumentPermissionList, -) - - -class DocumentInstance(InstanceResource): - """ - :ivar sid: - :ivar unique_name: - :ivar account_sid: - :ivar service_sid: - :ivar url: - :ivar links: - :ivar revision: - :ivar data: - :ivar date_created: - :ivar date_updated: - :ivar created_by: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.revision: Optional[str] = payload.get("revision") - self.data: Optional[Dict[str, object]] = payload.get("data") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.created_by: Optional[str] = payload.get("created_by") - - self._solution = { - "service_sid": service_sid, - "sid": sid or self.sid, - } - self._context: Optional[DocumentContext] = None - - @property - def _proxy(self) -> "DocumentContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DocumentContext for this DocumentInstance - """ - if self._context is None: - self._context = DocumentContext( - self._version, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DocumentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DocumentInstance": - """ - Fetch the DocumentInstance - - - :returns: The fetched DocumentInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DocumentInstance": - """ - Asynchronous coroutine to fetch the DocumentInstance - - - :returns: The fetched DocumentInstance - """ - return await self._proxy.fetch_async() - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "DocumentInstance": - """ - Update the DocumentInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - """ - return self._proxy.update( - data=data, - if_match=if_match, - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "DocumentInstance": - """ - Asynchronous coroutine to update the DocumentInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - """ - return await self._proxy.update_async( - data=data, - if_match=if_match, - ) - - @property - def document_permissions(self) -> DocumentPermissionList: - """ - Access the document_permissions - """ - return self._proxy.document_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.DocumentInstance {}>".format(context) - - -class DocumentContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, sid: str): - """ - Initialize the DocumentContext - - :param version: Version that contains the resource - :param service_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "sid": sid, - } - self._uri = "/Services/{service_sid}/Documents/{sid}".format(**self._solution) - - self._document_permissions: Optional[DocumentPermissionList] = None - - def delete(self) -> bool: - """ - Deletes the DocumentInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> DocumentInstance: - """ - Fetch the DocumentInstance - - - :returns: The fetched DocumentInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DocumentInstance: - """ - Asynchronous coroutine to fetch the DocumentInstance - - - :returns: The fetched DocumentInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> DocumentInstance: - """ - Update the DocumentInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> DocumentInstance: - """ - Asynchronous coroutine to update the DocumentInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated DocumentInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - @property - def document_permissions(self) -> DocumentPermissionList: - """ - Access the document_permissions - """ - if self._document_permissions is None: - self._document_permissions = DocumentPermissionList( - self._version, - self._solution["service_sid"], - self._solution["sid"], - ) - return self._document_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.DocumentContext {}>".format(context) - - -class DocumentPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: - """ - Build an instance of DocumentInstance - - :param payload: Payload response from the API - """ - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.DocumentPage>" - - -class DocumentList(ListResource): - - def __init__(self, version: Version, service_sid: str): - """ - Initialize the DocumentList - - :param version: Version that contains the resource - :param service_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - } - self._uri = "/Services/{service_sid}/Documents".format(**self._solution) - - def create( - self, - unique_name: Union[str, object] = values.unset, - data: Union[object, object] = values.unset, - ) -> DocumentInstance: - """ - Create the DocumentInstance - - :param unique_name: - :param data: - - :returns: The created DocumentInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, - unique_name: Union[str, object] = values.unset, - data: Union[object, object] = values.unset, - ) -> DocumentInstance: - """ - Asynchronously create the DocumentInstance - - :param unique_name: - :param data: - - :returns: The created DocumentInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DocumentInstance]: - """ - Streams DocumentInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DocumentInstance]: - """ - Asynchronously streams DocumentInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentInstance]: - """ - Lists DocumentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentInstance]: - """ - Asynchronously lists DocumentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DocumentPage: - """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DocumentPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DocumentPage: - """ - Asynchronously retrieve a single page of DocumentInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DocumentPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> DocumentPage: - """ - Retrieve a specific page of DocumentInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DocumentInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DocumentPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> DocumentPage: - """ - Asynchronously retrieve a specific page of DocumentInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DocumentInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DocumentPage(self._version, response, self._solution) - - def get(self, sid: str) -> DocumentContext: - """ - Constructs a DocumentContext - - :param sid: - """ - return DocumentContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __call__(self, sid: str) -> DocumentContext: - """ - Constructs a DocumentContext - - :param sid: - """ - return DocumentContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.DocumentList>" diff --git a/twilio/rest/preview/sync/service/document/document_permission.py b/twilio/rest/preview/sync/service/document/document_permission.py deleted file mode 100644 index 676efb569f..0000000000 --- a/twilio/rest/preview/sync/service/document/document_permission.py +++ /dev/null @@ -1,617 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class DocumentPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar document_sid: The unique SID identifier of the Sync Document to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync Document. - :ivar write: Boolean flag specifying whether the identity can update the Sync Document. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync Document. - :ivar url: Contains an absolute URL for this Sync Document Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - document_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.document_sid: Optional[str] = payload.get("document_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "document_sid": document_sid, - "identity": identity or self.identity, - } - self._context: Optional[DocumentPermissionContext] = None - - @property - def _proxy(self) -> "DocumentPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DocumentPermissionContext for this DocumentPermissionInstance - """ - if self._context is None: - self._context = DocumentPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DocumentPermissionInstance": - """ - Fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DocumentPermissionInstance": - """ - Asynchronous coroutine to fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "DocumentPermissionInstance": - """ - Update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "DocumentPermissionInstance": - """ - Asynchronous coroutine to update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.DocumentPermissionInstance {}>".format(context) - - -class DocumentPermissionContext(InstanceContext): - - def __init__( - self, version: Version, service_sid: str, document_sid: str, identity: str - ): - """ - Initialize the DocumentPermissionContext - - :param version: Version that contains the resource - :param service_sid: The unique SID identifier of the Sync Service Instance. - :param document_sid: Identifier of the Sync Document. Either a SID or a unique name. - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "document_sid": document_sid, - "identity": identity, - } - self._uri = "/Services/{service_sid}/Documents/{document_sid}/Permissions/{identity}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> DocumentPermissionInstance: - """ - Fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - - async def fetch_async(self) -> DocumentPermissionInstance: - """ - Asynchronous coroutine to fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - - def update( - self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: - """ - Update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: - """ - Asynchronous coroutine to update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.DocumentPermissionContext {}>".format(context) - - -class DocumentPermissionPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: - """ - Build an instance of DocumentPermissionInstance - - :param payload: Payload response from the API - """ - return DocumentPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.DocumentPermissionPage>" - - -class DocumentPermissionList(ListResource): - - def __init__(self, version: Version, service_sid: str, document_sid: str): - """ - Initialize the DocumentPermissionList - - :param version: Version that contains the resource - :param service_sid: - :param document_sid: Identifier of the Sync Document. Either a SID or a unique name. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "document_sid": document_sid, - } - self._uri = ( - "/Services/{service_sid}/Documents/{document_sid}/Permissions".format( - **self._solution - ) - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DocumentPermissionInstance]: - """ - Streams DocumentPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DocumentPermissionInstance]: - """ - Asynchronously streams DocumentPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentPermissionInstance]: - """ - Lists DocumentPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentPermissionInstance]: - """ - Asynchronously lists DocumentPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DocumentPermissionPage: - """ - Retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DocumentPermissionPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DocumentPermissionPage: - """ - Asynchronously retrieve a single page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return DocumentPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> DocumentPermissionPage: - """ - Retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DocumentPermissionInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DocumentPermissionPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> DocumentPermissionPage: - """ - Asynchronously retrieve a specific page of DocumentPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DocumentPermissionInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DocumentPermissionPage(self._version, response, self._solution) - - def get(self, identity: str) -> DocumentPermissionContext: - """ - Constructs a DocumentPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=identity, - ) - - def __call__(self, identity: str) -> DocumentPermissionContext: - """ - Constructs a DocumentPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return DocumentPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=identity, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.DocumentPermissionList>" diff --git a/twilio/rest/preview/sync/service/sync_list/__init__.py b/twilio/rest/preview/sync/service/sync_list/__init__.py deleted file mode 100644 index 0461f22430..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,595 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.preview.sync.service.sync_list.sync_list_item import SyncListItemList -from twilio.rest.preview.sync.service.sync_list.sync_list_permission import ( - SyncListPermissionList, -) - - -class SyncListInstance(InstanceResource): - """ - :ivar sid: - :ivar unique_name: - :ivar account_sid: - :ivar service_sid: - :ivar url: - :ivar links: - :ivar revision: - :ivar date_created: - :ivar date_updated: - :ivar created_by: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.revision: Optional[str] = payload.get("revision") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.created_by: Optional[str] = payload.get("created_by") - - self._solution = { - "service_sid": service_sid, - "sid": sid or self.sid, - } - self._context: Optional[SyncListContext] = None - - @property - def _proxy(self) -> "SyncListContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncListContext for this SyncListInstance - """ - if self._context is None: - self._context = SyncListContext( - self._version, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncListInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncListInstance": - """ - Fetch the SyncListInstance - - - :returns: The fetched SyncListInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncListInstance": - """ - Asynchronous coroutine to fetch the SyncListInstance - - - :returns: The fetched SyncListInstance - """ - return await self._proxy.fetch_async() - - @property - def sync_list_items(self) -> SyncListItemList: - """ - Access the sync_list_items - """ - return self._proxy.sync_list_items - - @property - def sync_list_permissions(self) -> SyncListPermissionList: - """ - Access the sync_list_permissions - """ - return self._proxy.sync_list_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListInstance {}>".format(context) - - -class SyncListContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, sid: str): - """ - Initialize the SyncListContext - - :param version: Version that contains the resource - :param service_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "sid": sid, - } - self._uri = "/Services/{service_sid}/Lists/{sid}".format(**self._solution) - - self._sync_list_items: Optional[SyncListItemList] = None - self._sync_list_permissions: Optional[SyncListPermissionList] = None - - def delete(self) -> bool: - """ - Deletes the SyncListInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncListInstance: - """ - Fetch the SyncListInstance - - - :returns: The fetched SyncListInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncListInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> SyncListInstance: - """ - Asynchronous coroutine to fetch the SyncListInstance - - - :returns: The fetched SyncListInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncListInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - @property - def sync_list_items(self) -> SyncListItemList: - """ - Access the sync_list_items - """ - if self._sync_list_items is None: - self._sync_list_items = SyncListItemList( - self._version, - self._solution["service_sid"], - self._solution["sid"], - ) - return self._sync_list_items - - @property - def sync_list_permissions(self) -> SyncListPermissionList: - """ - Access the sync_list_permissions - """ - if self._sync_list_permissions is None: - self._sync_list_permissions = SyncListPermissionList( - self._version, - self._solution["service_sid"], - self._solution["sid"], - ) - return self._sync_list_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListContext {}>".format(context) - - -class SyncListPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: - """ - Build an instance of SyncListInstance - - :param payload: Payload response from the API - """ - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListPage>" - - -class SyncListList(ListResource): - - def __init__(self, version: Version, service_sid: str): - """ - Initialize the SyncListList - - :param version: Version that contains the resource - :param service_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - } - self._uri = "/Services/{service_sid}/Lists".format(**self._solution) - - def create( - self, unique_name: Union[str, object] = values.unset - ) -> SyncListInstance: - """ - Create the SyncListInstance - - :param unique_name: - - :returns: The created SyncListInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, unique_name: Union[str, object] = values.unset - ) -> SyncListInstance: - """ - Asynchronously create the SyncListInstance - - :param unique_name: - - :returns: The created SyncListInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncListInstance]: - """ - Streams SyncListInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncListInstance]: - """ - Asynchronously streams SyncListInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListInstance]: - """ - Lists SyncListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListInstance]: - """ - Asynchronously lists SyncListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListPage: - """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListPage: - """ - Asynchronously retrieve a single page of SyncListInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncListPage: - """ - Retrieve a specific page of SyncListInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncListPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncListPage: - """ - Asynchronously retrieve a specific page of SyncListInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListPage(self._version, response, self._solution) - - def get(self, sid: str) -> SyncListContext: - """ - Constructs a SyncListContext - - :param sid: - """ - return SyncListContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __call__(self, sid: str) -> SyncListContext: - """ - Constructs a SyncListContext - - :param sid: - """ - return SyncListContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListList>" diff --git a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py b/twilio/rest/preview/sync/service/sync_list/sync_list_item.py deleted file mode 100644 index 5220aec215..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py +++ /dev/null @@ -1,763 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncListItemInstance(InstanceResource): - - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" - - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" - - """ - :ivar index: - :ivar account_sid: - :ivar service_sid: - :ivar list_sid: - :ivar url: - :ivar revision: - :ivar data: - :ivar date_created: - :ivar date_updated: - :ivar created_by: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - list_sid: str, - index: Optional[int] = None, - ): - super().__init__(version) - - self.index: Optional[int] = deserialize.integer(payload.get("index")) - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.list_sid: Optional[str] = payload.get("list_sid") - self.url: Optional[str] = payload.get("url") - self.revision: Optional[str] = payload.get("revision") - self.data: Optional[Dict[str, object]] = payload.get("data") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.created_by: Optional[str] = payload.get("created_by") - - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - "index": index or self.index, - } - self._context: Optional[SyncListItemContext] = None - - @property - def _proxy(self) -> "SyncListItemContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncListItemContext for this SyncListItemInstance - """ - if self._context is None: - self._context = SyncListItemContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], - ) - return self._context - - def delete(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Deletes the SyncListItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete( - if_match=if_match, - ) - - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Asynchronous coroutine that deletes the SyncListItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async( - if_match=if_match, - ) - - def fetch(self) -> "SyncListItemInstance": - """ - Fetch the SyncListItemInstance - - - :returns: The fetched SyncListItemInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncListItemInstance": - """ - Asynchronous coroutine to fetch the SyncListItemInstance - - - :returns: The fetched SyncListItemInstance - """ - return await self._proxy.fetch_async() - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "SyncListItemInstance": - """ - Update the SyncListItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - """ - return self._proxy.update( - data=data, - if_match=if_match, - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "SyncListItemInstance": - """ - Asynchronous coroutine to update the SyncListItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - """ - return await self._proxy.update_async( - data=data, - if_match=if_match, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListItemInstance {}>".format(context) - - -class SyncListItemContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): - """ - Initialize the SyncListItemContext - - :param version: Version that contains the resource - :param service_sid: - :param list_sid: - :param index: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - "index": index, - } - self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items/{index}".format( - **self._solution - ) - - def delete(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Deletes the SyncListItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - headers = values.of( - { - "If-Match": if_match, - } - ) - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Asynchronous coroutine that deletes the SyncListItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - headers = values.of( - { - "If-Match": if_match, - } - ) - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncListItemInstance: - """ - Fetch the SyncListItemInstance - - - :returns: The fetched SyncListItemInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], - ) - - async def fetch_async(self) -> SyncListItemInstance: - """ - Asynchronous coroutine to fetch the SyncListItemInstance - - - :returns: The fetched SyncListItemInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], - ) - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> SyncListItemInstance: - """ - Update the SyncListItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> SyncListItemInstance: - """ - Asynchronous coroutine to update the SyncListItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncListItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListItemContext {}>".format(context) - - -class SyncListItemPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: - """ - Build an instance of SyncListItemInstance - - :param payload: Payload response from the API - """ - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListItemPage>" - - -class SyncListItemList(ListResource): - - def __init__(self, version: Version, service_sid: str, list_sid: str): - """ - Initialize the SyncListItemList - - :param version: Version that contains the resource - :param service_sid: - :param list_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - } - self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items".format( - **self._solution - ) - - def create(self, data: object) -> SyncListItemInstance: - """ - Create the SyncListItemInstance - - :param data: - - :returns: The created SyncListItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - async def create_async(self, data: object) -> SyncListItemInstance: - """ - Asynchronously create the SyncListItemInstance - - :param data: - - :returns: The created SyncListItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - def stream( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncListItemInstance]: - """ - Streams SyncListItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncListItemInstance]: - """ - Asynchronously streams SyncListItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListItemInstance]: - """ - Lists SyncListItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListItemInstance]: - """ - Asynchronously lists SyncListItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListItemPage: - """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListItemPage(self._version, response, self._solution) - - async def page_async( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListItemPage: - """ - Asynchronously retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListItemPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncListItemPage: - """ - Retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListItemInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncListItemPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncListItemPage: - """ - Asynchronously retrieve a specific page of SyncListItemInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListItemInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListItemPage(self._version, response, self._solution) - - def get(self, index: int) -> SyncListItemContext: - """ - Constructs a SyncListItemContext - - :param index: - """ - return SyncListItemContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=index, - ) - - def __call__(self, index: int) -> SyncListItemContext: - """ - Constructs a SyncListItemContext - - :param index: - """ - return SyncListItemContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=index, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListItemList>" diff --git a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py b/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py deleted file mode 100644 index 334b62dd18..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py +++ /dev/null @@ -1,617 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncListPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar list_sid: The unique SID identifier of the Sync List to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync List and its Items. - :ivar write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync List. - :ivar url: Contains an absolute URL for this Sync List Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - list_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.list_sid: Optional[str] = payload.get("list_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - "identity": identity or self.identity, - } - self._context: Optional[SyncListPermissionContext] = None - - @property - def _proxy(self) -> "SyncListPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncListPermissionContext for this SyncListPermissionInstance - """ - if self._context is None: - self._context = SyncListPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncListPermissionInstance": - """ - Fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncListPermissionInstance": - """ - Asynchronous coroutine to fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "SyncListPermissionInstance": - """ - Update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "SyncListPermissionInstance": - """ - Asynchronous coroutine to update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListPermissionInstance {}>".format(context) - - -class SyncListPermissionContext(InstanceContext): - - def __init__( - self, version: Version, service_sid: str, list_sid: str, identity: str - ): - """ - Initialize the SyncListPermissionContext - - :param version: Version that contains the resource - :param service_sid: The unique SID identifier of the Sync Service Instance. - :param list_sid: Identifier of the Sync List. Either a SID or a unique name. - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - "identity": identity, - } - self._uri = ( - "/Services/{service_sid}/Lists/{list_sid}/Permissions/{identity}".format( - **self._solution - ) - ) - - def delete(self) -> bool: - """ - Deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncListPermissionInstance: - """ - Fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - - async def fetch_async(self) -> SyncListPermissionInstance: - """ - Asynchronous coroutine to fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: - """ - Update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: - """ - Asynchronous coroutine to update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncListPermissionContext {}>".format(context) - - -class SyncListPermissionPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: - """ - Build an instance of SyncListPermissionInstance - - :param payload: Payload response from the API - """ - return SyncListPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListPermissionPage>" - - -class SyncListPermissionList(ListResource): - - def __init__(self, version: Version, service_sid: str, list_sid: str): - """ - Initialize the SyncListPermissionList - - :param version: Version that contains the resource - :param service_sid: - :param list_sid: Identifier of the Sync List. Either a SID or a unique name. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - } - self._uri = "/Services/{service_sid}/Lists/{list_sid}/Permissions".format( - **self._solution - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncListPermissionInstance]: - """ - Streams SyncListPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncListPermissionInstance]: - """ - Asynchronously streams SyncListPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListPermissionInstance]: - """ - Lists SyncListPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListPermissionInstance]: - """ - Asynchronously lists SyncListPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListPermissionPage: - """ - Retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListPermissionPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListPermissionPage: - """ - Asynchronously retrieve a single page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncListPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncListPermissionPage: - """ - Retrieve a specific page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListPermissionInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncListPermissionPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncListPermissionPage: - """ - Asynchronously retrieve a specific page of SyncListPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncListPermissionInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListPermissionPage(self._version, response, self._solution) - - def get(self, identity: str) -> SyncListPermissionContext: - """ - Constructs a SyncListPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=identity, - ) - - def __call__(self, identity: str) -> SyncListPermissionContext: - """ - Constructs a SyncListPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return SyncListPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=identity, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncListPermissionList>" diff --git a/twilio/rest/preview/sync/service/sync_map/__init__.py b/twilio/rest/preview/sync/service/sync_map/__init__.py deleted file mode 100644 index 0ecbb6132f..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,593 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.preview.sync.service.sync_map.sync_map_item import SyncMapItemList -from twilio.rest.preview.sync.service.sync_map.sync_map_permission import ( - SyncMapPermissionList, -) - - -class SyncMapInstance(InstanceResource): - """ - :ivar sid: - :ivar unique_name: - :ivar account_sid: - :ivar service_sid: - :ivar url: - :ivar links: - :ivar revision: - :ivar date_created: - :ivar date_updated: - :ivar created_by: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.revision: Optional[str] = payload.get("revision") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.created_by: Optional[str] = payload.get("created_by") - - self._solution = { - "service_sid": service_sid, - "sid": sid or self.sid, - } - self._context: Optional[SyncMapContext] = None - - @property - def _proxy(self) -> "SyncMapContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncMapContext for this SyncMapInstance - """ - if self._context is None: - self._context = SyncMapContext( - self._version, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncMapInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncMapInstance": - """ - Fetch the SyncMapInstance - - - :returns: The fetched SyncMapInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncMapInstance": - """ - Asynchronous coroutine to fetch the SyncMapInstance - - - :returns: The fetched SyncMapInstance - """ - return await self._proxy.fetch_async() - - @property - def sync_map_items(self) -> SyncMapItemList: - """ - Access the sync_map_items - """ - return self._proxy.sync_map_items - - @property - def sync_map_permissions(self) -> SyncMapPermissionList: - """ - Access the sync_map_permissions - """ - return self._proxy.sync_map_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapInstance {}>".format(context) - - -class SyncMapContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, sid: str): - """ - Initialize the SyncMapContext - - :param version: Version that contains the resource - :param service_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "sid": sid, - } - self._uri = "/Services/{service_sid}/Maps/{sid}".format(**self._solution) - - self._sync_map_items: Optional[SyncMapItemList] = None - self._sync_map_permissions: Optional[SyncMapPermissionList] = None - - def delete(self) -> bool: - """ - Deletes the SyncMapInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncMapInstance: - """ - Fetch the SyncMapInstance - - - :returns: The fetched SyncMapInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncMapInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> SyncMapInstance: - """ - Asynchronous coroutine to fetch the SyncMapInstance - - - :returns: The fetched SyncMapInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncMapInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - @property - def sync_map_items(self) -> SyncMapItemList: - """ - Access the sync_map_items - """ - if self._sync_map_items is None: - self._sync_map_items = SyncMapItemList( - self._version, - self._solution["service_sid"], - self._solution["sid"], - ) - return self._sync_map_items - - @property - def sync_map_permissions(self) -> SyncMapPermissionList: - """ - Access the sync_map_permissions - """ - if self._sync_map_permissions is None: - self._sync_map_permissions = SyncMapPermissionList( - self._version, - self._solution["service_sid"], - self._solution["sid"], - ) - return self._sync_map_permissions - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapContext {}>".format(context) - - -class SyncMapPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: - """ - Build an instance of SyncMapInstance - - :param payload: Payload response from the API - """ - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapPage>" - - -class SyncMapList(ListResource): - - def __init__(self, version: Version, service_sid: str): - """ - Initialize the SyncMapList - - :param version: Version that contains the resource - :param service_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - } - self._uri = "/Services/{service_sid}/Maps".format(**self._solution) - - def create(self, unique_name: Union[str, object] = values.unset) -> SyncMapInstance: - """ - Create the SyncMapInstance - - :param unique_name: - - :returns: The created SyncMapInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, unique_name: Union[str, object] = values.unset - ) -> SyncMapInstance: - """ - Asynchronously create the SyncMapInstance - - :param unique_name: - - :returns: The created SyncMapInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncMapInstance]: - """ - Streams SyncMapInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncMapInstance]: - """ - Asynchronously streams SyncMapInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapInstance]: - """ - Lists SyncMapInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapInstance]: - """ - Asynchronously lists SyncMapInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapPage: - """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapPage: - """ - Asynchronously retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncMapPage: - """ - Retrieve a specific page of SyncMapInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncMapPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncMapPage: - """ - Asynchronously retrieve a specific page of SyncMapInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapPage(self._version, response, self._solution) - - def get(self, sid: str) -> SyncMapContext: - """ - Constructs a SyncMapContext - - :param sid: - """ - return SyncMapContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __call__(self, sid: str) -> SyncMapContext: - """ - Constructs a SyncMapContext - - :param sid: - """ - return SyncMapContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapList>" diff --git a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py b/twilio/rest/preview/sync/service/sync_map/sync_map_item.py deleted file mode 100644 index 9ddd1d5afe..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py +++ /dev/null @@ -1,767 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncMapItemInstance(InstanceResource): - - class QueryFromBoundType(object): - INCLUSIVE = "inclusive" - EXCLUSIVE = "exclusive" - - class QueryResultOrder(object): - ASC = "asc" - DESC = "desc" - - """ - :ivar key: - :ivar account_sid: - :ivar service_sid: - :ivar map_sid: - :ivar url: - :ivar revision: - :ivar data: - :ivar date_created: - :ivar date_updated: - :ivar created_by: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - map_sid: str, - key: Optional[str] = None, - ): - super().__init__(version) - - self.key: Optional[str] = payload.get("key") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.map_sid: Optional[str] = payload.get("map_sid") - self.url: Optional[str] = payload.get("url") - self.revision: Optional[str] = payload.get("revision") - self.data: Optional[Dict[str, object]] = payload.get("data") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.created_by: Optional[str] = payload.get("created_by") - - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - "key": key or self.key, - } - self._context: Optional[SyncMapItemContext] = None - - @property - def _proxy(self) -> "SyncMapItemContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncMapItemContext for this SyncMapItemInstance - """ - if self._context is None: - self._context = SyncMapItemContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], - ) - return self._context - - def delete(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Deletes the SyncMapItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete( - if_match=if_match, - ) - - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async( - if_match=if_match, - ) - - def fetch(self) -> "SyncMapItemInstance": - """ - Fetch the SyncMapItemInstance - - - :returns: The fetched SyncMapItemInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncMapItemInstance": - """ - Asynchronous coroutine to fetch the SyncMapItemInstance - - - :returns: The fetched SyncMapItemInstance - """ - return await self._proxy.fetch_async() - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "SyncMapItemInstance": - """ - Update the SyncMapItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - """ - return self._proxy.update( - data=data, - if_match=if_match, - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> "SyncMapItemInstance": - """ - Asynchronous coroutine to update the SyncMapItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - """ - return await self._proxy.update_async( - data=data, - if_match=if_match, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapItemInstance {}>".format(context) - - -class SyncMapItemContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): - """ - Initialize the SyncMapItemContext - - :param version: Version that contains the resource - :param service_sid: - :param map_sid: - :param key: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - "key": key, - } - self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items/{key}".format( - **self._solution - ) - - def delete(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Deletes the SyncMapItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - headers = values.of( - { - "If-Match": if_match, - } - ) - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapItemInstance - - :param if_match: The If-Match HTTP request header - - :returns: True if delete succeeds, False otherwise - """ - headers = values.of( - { - "If-Match": if_match, - } - ) - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncMapItemInstance: - """ - Fetch the SyncMapItemInstance - - - :returns: The fetched SyncMapItemInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], - ) - - async def fetch_async(self) -> SyncMapItemInstance: - """ - Asynchronous coroutine to fetch the SyncMapItemInstance - - - :returns: The fetched SyncMapItemInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], - ) - - def update( - self, data: object, if_match: Union[str, object] = values.unset - ) -> SyncMapItemInstance: - """ - Update the SyncMapItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], - ) - - async def update_async( - self, data: object, if_match: Union[str, object] = values.unset - ) -> SyncMapItemInstance: - """ - Asynchronous coroutine to update the SyncMapItemInstance - - :param data: - :param if_match: The If-Match HTTP request header - - :returns: The updated SyncMapItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapItemContext {}>".format(context) - - -class SyncMapItemPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: - """ - Build an instance of SyncMapItemInstance - - :param payload: Payload response from the API - """ - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapItemPage>" - - -class SyncMapItemList(ListResource): - - def __init__(self, version: Version, service_sid: str, map_sid: str): - """ - Initialize the SyncMapItemList - - :param version: Version that contains the resource - :param service_sid: - :param map_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - } - self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items".format( - **self._solution - ) - - def create(self, key: str, data: object) -> SyncMapItemInstance: - """ - Create the SyncMapItemInstance - - :param key: - :param data: - - :returns: The created SyncMapItemInstance - """ - - data = values.of( - { - "Key": key, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - async def create_async(self, key: str, data: object) -> SyncMapItemInstance: - """ - Asynchronously create the SyncMapItemInstance - - :param key: - :param data: - - :returns: The created SyncMapItemInstance - """ - - data = values.of( - { - "Key": key, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - def stream( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncMapItemInstance]: - """ - Streams SyncMapItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncMapItemInstance]: - """ - Asynchronously streams SyncMapItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapItemInstance]: - """ - Lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapItemInstance]: - """ - Asynchronously lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapItemPage: - """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapItemPage(self._version, response, self._solution) - - async def page_async( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapItemPage: - """ - Asynchronously retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapItemPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncMapItemPage: - """ - Retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapItemInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncMapItemPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncMapItemPage: - """ - Asynchronously retrieve a specific page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapItemInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapItemPage(self._version, response, self._solution) - - def get(self, key: str) -> SyncMapItemContext: - """ - Constructs a SyncMapItemContext - - :param key: - """ - return SyncMapItemContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=key, - ) - - def __call__(self, key: str) -> SyncMapItemContext: - """ - Constructs a SyncMapItemContext - - :param key: - """ - return SyncMapItemContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=key, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapItemList>" diff --git a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py b/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py deleted file mode 100644 index 9e19d56a91..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py +++ /dev/null @@ -1,615 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncMapPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar map_sid: The unique SID identifier of the Sync Map to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync Map and its Items. - :ivar write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync Map. - :ivar url: Contains an absolute URL for this Sync Map Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - map_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.map_sid: Optional[str] = payload.get("map_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - "identity": identity or self.identity, - } - self._context: Optional[SyncMapPermissionContext] = None - - @property - def _proxy(self) -> "SyncMapPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncMapPermissionContext for this SyncMapPermissionInstance - """ - if self._context is None: - self._context = SyncMapPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncMapPermissionInstance": - """ - Fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncMapPermissionInstance": - """ - Asynchronous coroutine to fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "SyncMapPermissionInstance": - """ - Update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "SyncMapPermissionInstance": - """ - Asynchronous coroutine to update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapPermissionInstance {}>".format(context) - - -class SyncMapPermissionContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): - """ - Initialize the SyncMapPermissionContext - - :param version: Version that contains the resource - :param service_sid: The unique SID identifier of the Sync Service Instance. - :param map_sid: Identifier of the Sync Map. Either a SID or a unique name. - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - "identity": identity, - } - self._uri = ( - "/Services/{service_sid}/Maps/{map_sid}/Permissions/{identity}".format( - **self._solution - ) - ) - - def delete(self) -> bool: - """ - Deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncMapPermissionInstance: - """ - Fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - - async def fetch_async(self) -> SyncMapPermissionInstance: - """ - Asynchronous coroutine to fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: - """ - Update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: - """ - Asynchronous coroutine to update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - - data = values.of( - { - "Read": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(manage), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Preview.Sync.SyncMapPermissionContext {}>".format(context) - - -class SyncMapPermissionPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: - """ - Build an instance of SyncMapPermissionInstance - - :param payload: Payload response from the API - """ - return SyncMapPermissionInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapPermissionPage>" - - -class SyncMapPermissionList(ListResource): - - def __init__(self, version: Version, service_sid: str, map_sid: str): - """ - Initialize the SyncMapPermissionList - - :param version: Version that contains the resource - :param service_sid: - :param map_sid: Identifier of the Sync Map. Either a SID or a unique name. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - } - self._uri = "/Services/{service_sid}/Maps/{map_sid}/Permissions".format( - **self._solution - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncMapPermissionInstance]: - """ - Streams SyncMapPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncMapPermissionInstance]: - """ - Asynchronously streams SyncMapPermissionInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapPermissionInstance]: - """ - Lists SyncMapPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapPermissionInstance]: - """ - Asynchronously lists SyncMapPermissionInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapPermissionPage: - """ - Retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapPermissionPage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapPermissionPage: - """ - Asynchronously retrieve a single page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapPermissionInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return SyncMapPermissionPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SyncMapPermissionPage: - """ - Retrieve a specific page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapPermissionInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SyncMapPermissionPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: - """ - Asynchronously retrieve a specific page of SyncMapPermissionInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SyncMapPermissionInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapPermissionPage(self._version, response, self._solution) - - def get(self, identity: str) -> SyncMapPermissionContext: - """ - Constructs a SyncMapPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=identity, - ) - - def __call__(self, identity: str) -> SyncMapPermissionContext: - """ - Constructs a SyncMapPermissionContext - - :param identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - """ - return SyncMapPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=identity, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Preview.Sync.SyncMapPermissionList>" diff --git a/twilio/rest/preview/wireless/command.py b/twilio/rest/preview/wireless/command.py index 8e715e09ef..1ca73b5b3b 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CommandContext] = None @property @@ -96,6 +98,24 @@ async def fetch_async(self) -> "CommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -123,48 +143,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Commands/{sid}".format(**self._solution) - def fetch(self) -> CommandInstance: + def _fetch(self) -> tuple: """ - Fetch the CommandInstance - + Internal helper for fetch operation - :returns: The fetched CommandInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + payload, _, _ = self._fetch() return CommandInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CommandInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CommandInstance + Fetch the CommandInstance and return response metadata - :returns: The fetched CommandInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + payload, _, _ = await self._fetch_async() return CommandInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -183,6 +251,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -207,7 +276,7 @@ def __init__(self, version: Version): self._uri = "/Commands" - def create( + def _create( self, command: str, device: Union[str, object] = values.unset, @@ -216,19 +285,12 @@ def create( callback_url: Union[str, object] = values.unset, command_mode: Union[str, object] = values.unset, include_sid: Union[str, object] = values.unset, - ) -> CommandInstance: + ) -> tuple: """ - Create the CommandInstance - - :param command: - :param device: - :param sim: - :param callback_method: - :param callback_url: - :param command_mode: - :param include_sid: + Internal helper for create operation - :returns: The created CommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -248,13 +310,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CommandInstance(self._version, payload) - - async def create_async( + def create( self, command: str, device: Union[str, object] = values.unset, @@ -265,7 +325,7 @@ async def create_async( include_sid: Union[str, object] = values.unset, ) -> CommandInstance: """ - Asynchronously create the CommandInstance + Create the CommandInstance :param command: :param device: @@ -277,6 +337,68 @@ async def create_async( :returns: The created CommandInstance """ + payload, _, _ = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -295,12 +417,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + payload, _, _ = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) return CommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, device: Union[str, object] = values.unset, @@ -379,6 +568,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CommandInstance and returns headers from first page + + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CommandInstance and returns headers from first page + + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, device: Union[str, object] = values.unset, @@ -406,6 +671,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( device=device, @@ -444,6 +710,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -456,6 +723,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CommandInstance and returns headers from first page + + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CommandInstance and returns headers from first page + + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, device: Union[str, object] = values.unset, @@ -546,6 +887,100 @@ async def page_async( ) return CommandPage(self._version, response) + def page_with_http_info( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommandPage, status code, and headers + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommandPage, status code, and headers + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CommandPage: """ Retrieve a specific page of CommandInstance records from the API. diff --git a/twilio/rest/preview/wireless/rate_plan.py b/twilio/rest/preview/wireless/rate_plan.py index 95e45f1ef2..46a4445e4d 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RatePlanInstance": """ Fetch the RatePlanInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "RatePlanInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -160,6 +198,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance with HTTP info + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -187,6 +261,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RatePlans/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RatePlanInstance @@ -194,10 +282,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -206,67 +316,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RatePlanInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RatePlanInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = self._fetch() return RatePlanInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> RatePlanInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RatePlanInstance + Fetch the RatePlanInstance and return response metadata - :returns: The fetched RatePlanInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = await self._fetch_async() return RatePlanInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> RatePlanInstance: + ) -> tuple: """ - Update the RatePlanInstance - - :param unique_name: - :param friendly_name: + Internal helper for update operation - :returns: The updated RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,25 +443,58 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, ) -> RatePlanInstance: """ - Asynchronous coroutine to update the RatePlanInstance + Update the RatePlanInstance :param unique_name: :param friendly_name: :returns: The updated RatePlanInstance """ + payload, _, _ = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -313,12 +508,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -337,6 +567,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -361,7 +592,7 @@ def __init__(self, version: Version): self._uri = "/RatePlans" - def create( + def _create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -373,22 +604,12 @@ def create( commands_enabled: Union[bool, object] = values.unset, national_roaming_enabled: Union[bool, object] = values.unset, international_roaming: Union[List[str], object] = values.unset, - ) -> RatePlanInstance: + ) -> tuple: """ - Create the RatePlanInstance + Internal helper for create operation - :param unique_name: - :param friendly_name: - :param data_enabled: - :param data_limit: - :param data_metering: - :param messaging_enabled: - :param voice_enabled: - :param commands_enabled: - :param national_roaming_enabled: - :param international_roaming: - - :returns: The created RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,13 +636,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -435,7 +654,7 @@ async def create_async( international_roaming: Union[List[str], object] = values.unset, ) -> RatePlanInstance: """ - Asynchronously create the RatePlanInstance + Create the RatePlanInstance :param unique_name: :param friendly_name: @@ -450,6 +669,83 @@ async def create_async( :returns: The created RatePlanInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -475,12 +771,97 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) return RatePlanInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -531,6 +912,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -550,6 +981,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -576,6 +1008,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -584,6 +1017,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -650,6 +1133,76 @@ async def page_async( ) return RatePlanPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RatePlanPage: """ Retrieve a specific page of RatePlanInstance records from the API. diff --git a/twilio/rest/preview/wireless/sim/__init__.py b/twilio/rest/preview/wireless/sim/__init__.py index 07a9e74da0..ac6b78788d 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -121,6 +123,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -241,6 +261,126 @@ async def update_async( voice_url=voice_url, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + @property def usage(self) -> UsageList: """ @@ -277,48 +417,152 @@ def __init__(self, version: Version, sid: str): self._usage: Optional[UsageList] = None - def fetch(self) -> SimInstance: + def _fetch(self) -> tuple: """ - Fetch the SimInstance + Internal helper for fetch operation - - :returns: The fetched SimInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + :returns: The fetched SimInstance + """ + payload, _, _ = self._fetch() return SimInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SimInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SimInstance + Fetch the SimInstance and return response metadata - :returns: The fetched SimInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = await self._fetch_async() return SimInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def update( self, unique_name: Union[str, object] = values.unset, @@ -360,6 +604,113 @@ def update( :returns: The updated SimInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -387,12 +738,10 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return SimInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, unique_name: Union[str, object] = values.unset, @@ -434,38 +783,87 @@ async def update_async( :returns: The updated SimInstance """ - - data = values.of( - { - "UniqueName": unique_name, - "CallbackMethod": callback_method, - "CallbackUrl": callback_url, - "FriendlyName": friendly_name, - "RatePlan": rate_plan, - "Status": status, - "CommandsCallbackMethod": commands_callback_method, - "CommandsCallbackUrl": commands_callback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsMethod": sms_method, - "SmsUrl": sms_url, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - } + payload, _, _ = await self._update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, ) - headers = values.of({}) + return SimInstance(self._version, payload, sid=self._solution["sid"]) - headers["Content-Type"] = "application/x-www-form-urlencoded" + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata - headers["Accept"] = "application/json" + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, ) - - return SimInstance(self._version, payload, sid=self._solution["sid"]) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def usage(self) -> UsageList: @@ -497,6 +895,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -605,6 +1004,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimInstance and returns headers from first page + + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union[str, object] = values.unset, @@ -634,6 +1115,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -675,6 +1157,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -688,6 +1171,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union[str, object] = values.unset, @@ -784,6 +1347,106 @@ async def page_async( ) return SimPage(self._version, response) + def page_with_http_info( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SimPage: """ Retrieve a specific page of SimInstance records from the API. diff --git a/twilio/rest/preview/wireless/sim/usage.py b/twilio/rest/preview/wireless/sim/usage.py index aff3731b51..33010acf35 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): self._solution = { "sim_sid": sim_sid, } + self._context: Optional[UsageContext] = None @property @@ -102,6 +104,42 @@ async def fetch_async( start=start, ) + def fetch_with_http_info( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the UsageInstance with HTTP info + + :param end: + :param start: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end=end, + start=start, + ) + + async def fetch_with_http_info_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsageInstance with HTTP info + + :param end: + :param start: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end=end, + start=start, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -129,21 +167,19 @@ def __init__(self, version: Version, sim_sid: str): } self._uri = "/Sims/{sim_sid}/Usage".format(**self._solution) - def fetch( + def _fetch( self, end: Union[str, object] = values.unset, start: Union[str, object] = values.unset, - ) -> UsageInstance: + ) -> tuple: """ - Fetch the UsageInstance + Internal helper for fetch operation - :param end: - :param start: - - :returns: The fetched UsageInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "End": end, "Start": start, @@ -154,31 +190,64 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + payload, _, _ = self._fetch(end=end, start=start) return UsageInstance( self._version, payload, sim_sid=self._solution["sim_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end: Union[str, object] = values.unset, start: Union[str, object] = values.unset, - ) -> UsageInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the UsageInstance + Fetch the UsageInstance and return response metadata :param end: :param start: - :returns: The fetched UsageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(end=end, start=start) + instance = UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "End": end, "Start": start, @@ -189,16 +258,51 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Asynchronous coroutine to fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + payload, _, _ = await self._fetch_async(end=end, start=start) return UsageInstance( self._version, payload, sim_sid=self._solution["sim_sid"], ) + async def fetch_with_http_info_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsageInstance and return response metadata + + :param end: + :param start: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(end=end, start=start) + instance = UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/preview_iam/v1/authorize.py b/twilio/rest/preview_iam/v1/authorize.py index 4166b4aea2..e011a3d2ae 100644 --- a/twilio/rest/preview_iam/v1/authorize.py +++ b/twilio/rest/preview_iam/v1/authorize.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,19 +54,19 @@ def __init__(self, version: Version): self._uri = "/authorize" - def fetch( + def _fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, redirect_uri: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, state: Union[str, object] = values.unset, - ) -> AuthorizeInstance: + ) -> tuple: """ - Asynchronously fetch the AuthorizeInstance + Internal helper for fetch operation - :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback - :returns: The fetched AuthorizeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -81,13 +82,11 @@ def fetch( } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) - return AuthorizeInstance(self._version, payload) - - async def fetch_async( + def fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, @@ -96,11 +95,58 @@ async def fetch_async( state: Union[str, object] = values.unset, ) -> AuthorizeInstance: """ - Asynchronously fetch the AuthorizeInstance + Fetch the AuthorizeInstance :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback :returns: The fetched AuthorizeInstance """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" @@ -115,12 +161,57 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) return AuthorizeInstance(self._version, payload) + async def fetch_with_http_info_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/preview_iam/v1/token.py b/twilio/rest/preview_iam/v1/token.py index 34d9f30080..9a496553a6 100644 --- a/twilio/rest/preview_iam/v1/token.py +++ b/twilio/rest/preview_iam/v1/token.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,7 +62,7 @@ def __init__(self, version: Version): self._uri = "/token" - def create( + def _create( self, grant_type: str, client_id: str, @@ -71,20 +72,12 @@ def create( audience: Union[str, object] = values.unset, refresh_token: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, - ) -> TokenInstance: + ) -> tuple: """ - Create the TokenInstance - - :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. - :param client_id: A 34 character string that uniquely identifies this OAuth App. - :param client_secret: The credential for confidential OAuth App. - :param code: JWT token related to the authorization code grant type. - :param redirect_uri: The redirect uri - :param audience: The targeted audience uri - :param refresh_token: JWT token related to refresh access token. - :param scope: The scope of token + Internal helper for create operation - :returns: The created TokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -105,13 +98,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TokenInstance(self._version, payload) - - async def create_async( + def create( self, grant_type: str, client_id: str, @@ -123,7 +114,7 @@ async def create_async( scope: Union[str, object] = values.unset, ) -> TokenInstance: """ - Asynchronously create the TokenInstance + Create the TokenInstance :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. :param client_id: A 34 character string that uniquely identifies this OAuth App. @@ -136,6 +127,73 @@ async def create_async( :returns: The created TokenInstance """ + payload, _, _ = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -155,12 +213,85 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) return TokenInstance(self._version, payload) + async def create_with_http_info_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/preview_iam/versionless/organization/account.py b/twilio/rest/preview_iam/versionless/organization/account.py index f1c8019860..3ee97bd283 100644 --- a/twilio/rest/preview_iam/versionless/organization/account.py +++ b/twilio/rest/preview_iam/versionless/organization/account.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,7 +43,7 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") - self.status: Optional[str] = payload.get("status") + self.status: Optional["AccountInstance.str"] = payload.get("status") self.owner_sid: Optional[str] = payload.get("owner_sid") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -52,6 +53,7 @@ def __init__( "organization_sid": organization_sid, "account_sid": account_sid or self.account_sid, } + self._context: Optional[AccountContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "AccountInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,20 +139,30 @@ def __init__(self, version: Version, organization_sid: str, account_sid: str): **self._solution ) - def fetch(self) -> AccountInstance: + def _fetch(self) -> tuple: """ - Fetch the AccountInstance - + Internal helper for fetch operation - :returns: The fetched AccountInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = self._fetch() return AccountInstance( self._version, payload, @@ -140,22 +170,46 @@ def fetch(self) -> AccountInstance: account_sid=self._solution["account_sid"], ) - async def fetch_async(self) -> AccountInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AccountInstance + Fetch the AccountInstance and return response metadata - :returns: The fetched AccountInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = await self._fetch_async() return AccountInstance( self._version, payload, @@ -163,6 +217,22 @@ async def fetch_async(self) -> AccountInstance: account_sid=self._solution["account_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +251,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: :param payload: Payload response from the API """ + return AccountInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) @@ -262,6 +333,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -281,6 +402,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -307,6 +429,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -315,6 +438,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AccountInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -346,7 +519,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AccountPage(self._version, response, self._solution) + return AccountPage(self._version, response, solution=self._solution) async def page_async( self, @@ -379,7 +552,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AccountPage(self._version, response, self._solution) + return AccountPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AccountPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AccountPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AccountPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AccountPage: """ @@ -391,7 +634,7 @@ def get_page(self, target_url: str) -> AccountPage: :returns: Page of AccountInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AccountPage(self._version, response, self._solution) + return AccountPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AccountPage: """ @@ -403,7 +646,7 @@ async def get_page_async(self, target_url: str) -> AccountPage: :returns: Page of AccountInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AccountPage(self._version, response, self._solution) + return AccountPage(self._version, response, solution=self._solution) def get(self, account_sid: str) -> AccountContext: """ diff --git a/twilio/rest/preview_iam/versionless/organization/role_assignment.py b/twilio/rest/preview_iam/versionless/organization/role_assignment.py index 9d356f2c7c..860b077723 100644 --- a/twilio/rest/preview_iam/versionless/organization/role_assignment.py +++ b/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,8 @@ class PublicApiCreateRoleAssignmentRequest(object): :ivar role_sid: Twilio Role Sid representing assigned role :ivar scope: Twilio Sid representing scope of this assignment :ivar identity: Twilio Sid representing identity of this assignment + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments """ def __init__(self, payload: Dict[str, Any]): @@ -35,12 +38,16 @@ def __init__(self, payload: Dict[str, Any]): self.role_sid: Optional[str] = payload.get("role_sid") self.scope: Optional[str] = payload.get("scope") self.identity: Optional[str] = payload.get("identity") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") def to_dict(self): return { "role_sid": self.role_sid, "scope": self.scope, "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, } """ @@ -48,6 +55,8 @@ def to_dict(self): :ivar role_sid: Twilio Role Sid representing assigned role :ivar scope: Twilio Sid representing identity of this assignment :ivar identity: Twilio Sid representing scope of this assignment + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments :ivar code: Twilio-specific error code :ivar message: Error message :ivar more_info: Link to Error Code References @@ -67,6 +76,8 @@ def __init__( self.role_sid: Optional[str] = payload.get("role_sid") self.scope: Optional[str] = payload.get("scope") self.identity: Optional[str] = payload.get("identity") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") self.code: Optional[int] = payload.get("code") self.message: Optional[str] = payload.get("message") self.more_info: Optional[str] = payload.get("moreInfo") @@ -76,6 +87,7 @@ def __init__( "organization_sid": organization_sid, "sid": sid or self.sid, } + self._context: Optional[RoleAssignmentContext] = None @property @@ -112,6 +124,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -131,6 +161,8 @@ class PublicApiCreateRoleAssignmentRequest(object): :ivar role_sid: Twilio Role Sid representing assigned role :ivar scope: Twilio Sid representing scope of this assignment :ivar identity: Twilio Sid representing identity of this assignment + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments """ def __init__(self, payload: Dict[str, Any]): @@ -138,12 +170,16 @@ def __init__(self, payload: Dict[str, Any]): self.role_sid: Optional[str] = payload.get("role_sid") self.scope: Optional[str] = payload.get("scope") self.identity: Optional[str] = payload.get("identity") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") def to_dict(self): return { "role_sid": self.role_sid, "scope": self.scope, "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, } def __init__(self, version: Version, organization_sid: str, sid: str): @@ -163,6 +199,22 @@ def __init__(self, version: Version, organization_sid: str, sid: str): } self._uri = "/{organization_sid}/RoleAssignments/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleAssignmentInstance @@ -170,12 +222,34 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) headers["Accept"] = "application/scim+json" - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -184,14 +258,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance and return response metadata - headers["Accept"] = "application/scim+json" - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -213,6 +291,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleAssignmentInstance: :param payload: Payload response from the API """ + return RoleAssignmentInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) @@ -233,6 +312,8 @@ class PublicApiCreateRoleAssignmentRequest(object): :ivar role_sid: Twilio Role Sid representing assigned role :ivar scope: Twilio Sid representing scope of this assignment :ivar identity: Twilio Sid representing identity of this assignment + :ivar resource_type: The resource type for resource-level role assignments + :ivar resource_id: The resource id for resource-level role assignments """ def __init__(self, payload: Dict[str, Any]): @@ -240,12 +321,16 @@ def __init__(self, payload: Dict[str, Any]): self.role_sid: Optional[str] = payload.get("role_sid") self.scope: Optional[str] = payload.get("scope") self.identity: Optional[str] = payload.get("identity") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_id: Optional[str] = payload.get("resource_id") def to_dict(self): return { "role_sid": self.role_sid, "scope": self.scope, "identity": self.identity, + "resource_type": self.resource_type, + "resource_id": self.resource_id, } def __init__(self, version: Version, organization_sid: str): @@ -264,16 +349,15 @@ def __init__(self, version: Version, organization_sid: str): } self._uri = "/{organization_sid}/RoleAssignments".format(**self._solution) - def create( + def _create( self, public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, - ) -> RoleAssignmentInstance: + ) -> tuple: """ - Create the RoleAssignmentInstance + Internal helper for create operation - :param public_api_create_role_assignment_request: - - :returns: The created RoleAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = public_api_create_role_assignment_request.to_dict() @@ -283,24 +367,56 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + payload, _, _ = self._create( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) return RoleAssignmentInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) - async def create_async( + def create_with_http_info( self, public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, - ) -> RoleAssignmentInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleAssignmentInstance + Create the RoleAssignmentInstance and return response metadata :param public_api_create_role_assignment_request: - :returns: The created RoleAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + instance = RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = public_api_create_role_assignment_request.to_dict() @@ -310,18 +426,53 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Asynchronously create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + payload, _, _ = await self._create_async( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) return RoleAssignmentInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) + async def create_with_http_info_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> ApiResponse: + """ + Asynchronously create the RoleAssignmentInstance and return response metadata + + :param public_api_create_role_assignment_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + public_api_create_role_assignment_request=public_api_create_role_assignment_request + ) + instance = RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[RoleAssignmentInstance]: @@ -333,6 +484,8 @@ def stream( :param str identity: :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -343,7 +496,13 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(identity=identity, scope=scope, page_size=limits["page_size"]) + page = self.page( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) return self._version.stream(page, limits["limit"]) @@ -351,6 +510,8 @@ async def stream_async( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[RoleAssignmentInstance]: @@ -362,6 +523,8 @@ async def stream_async( :param str identity: :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -373,15 +536,97 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - identity=identity, scope=scope, page_size=limits["page_size"] + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[RoleAssignmentInstance]: @@ -392,6 +637,8 @@ def list( :param str identity: :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -401,10 +648,13 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, scope=scope, + resource_type=resource_type, + resource_id=resource_id, limit=limit, page_size=page_size, ) @@ -414,6 +664,8 @@ async def list_async( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[RoleAssignmentInstance]: @@ -424,6 +676,8 @@ async def list_async( :param str identity: :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -433,20 +687,99 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( identity=identity, scope=scope, + resource_type=resource_type, + resource_id=resource_id, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoleAssignmentInstance and returns headers from first page + + + :param str identity: + :param str scope: + :param str resource_type: Filter by resource type for resource-level role assignments + :param str resource_id: Filter by resource id for resource-level role assignments + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + scope=scope, + resource_type=resource_type, + resource_id=resource_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -457,6 +790,8 @@ def page( :param identity: :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -467,6 +802,8 @@ def page( { "Identity": identity, "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_id, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -480,12 +817,14 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RoleAssignmentPage(self._version, response, self._solution) + return RoleAssignmentPage(self._version, response, solution=self._solution) async def page_async( self, identity: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -496,6 +835,8 @@ async def page_async( :param identity: :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -506,6 +847,8 @@ async def page_async( { "Identity": identity, "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_id, "PageToken": page_token, "Page": page_number, "PageSize": page_size, @@ -519,7 +862,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RoleAssignmentPage(self._version, response, self._solution) + return RoleAssignmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoleAssignmentPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoleAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + resource_type: Union[str, object] = values.unset, + resource_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param identity: + :param scope: + :param resource_type: Filter by resource type for resource-level role assignments + :param resource_id: Filter by resource id for resource-level role assignments + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoleAssignmentPage, status code, and headers + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "ResourceType": resource_type, + "ResourceId": resource_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoleAssignmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RoleAssignmentPage: """ @@ -531,7 +968,7 @@ def get_page(self, target_url: str) -> RoleAssignmentPage: :returns: Page of RoleAssignmentInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RoleAssignmentPage(self._version, response, self._solution) + return RoleAssignmentPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RoleAssignmentPage: """ @@ -543,7 +980,7 @@ async def get_page_async(self, target_url: str) -> RoleAssignmentPage: :returns: Page of RoleAssignmentInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RoleAssignmentPage(self._version, response, self._solution) + return RoleAssignmentPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoleAssignmentContext: """ diff --git a/twilio/rest/preview_iam/versionless/organization/user.py b/twilio/rest/preview_iam/versionless/organization/user.py index 166f76b421..8299913b2c 100644 --- a/twilio/rest/preview_iam/versionless/organization/user.py +++ b/twilio/rest/preview_iam/versionless/organization/user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,16 +55,16 @@ class ScimMeta(object): def __init__(self, payload: Dict[str, Any]): - self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_type: Optional[str] = payload.get("resourceType") self.created: Optional[datetime] = payload.get("created") - self.last_modified: Optional[datetime] = payload.get("last_modified") + self.last_modified: Optional[datetime] = payload.get("lastModified") self.version: Optional[str] = payload.get("version") def to_dict(self): return { - "resource_type": self.resource_type, + "resourceType": self.resource_type, "created": self.created, - "last_modified": self.last_modified, + "lastModified": self.last_modified, "version": self.version, } @@ -75,13 +76,56 @@ class ScimName(object): def __init__(self, payload: Dict[str, Any]): - self.given_name: Optional[str] = payload.get("given_name") - self.family_name: Optional[str] = payload.get("family_name") + self.given_name: Optional[str] = payload.get("givenName") + self.family_name: Optional[str] = payload.get("familyName") def to_dict(self): return { - "given_name": self.given_name, - "family_name": self.family_name, + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) + + def to_dict(self): + return { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), } class ScimUser(object): @@ -107,9 +151,9 @@ class ScimUser(object): def __init__(self, payload: Dict[str, Any]): self.id: Optional[str] = payload.get("id") - self.external_id: Optional[str] = payload.get("external_id") - self.user_name: Optional[str] = payload.get("user_name") - self.display_name: Optional[str] = payload.get("display_name") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") self.name: Optional[UserList.ScimName] = payload.get("name") self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( "emails" @@ -120,10 +164,10 @@ def __init__(self, payload: Dict[str, Any]): self.schemas: Optional[List[str]] = payload.get("schemas") self.meta: Optional[UserList.ScimMeta] = payload.get("meta") self.detail: Optional[str] = payload.get("detail") - self.scim_type: Optional[str] = payload.get("scim_type") + self.scim_type: Optional["UserInstance.str"] = payload.get("scimType") self.status: Optional[str] = payload.get("status") self.code: Optional[int] = payload.get("code") - self.more_info: Optional[str] = payload.get("more_info") + self.more_info: Optional[str] = payload.get("moreInfo") def to_dict(self): return { @@ -189,7 +233,7 @@ def __init__( self.schemas: Optional[List[str]] = payload.get("schemas") self.meta: Optional[UserList.str] = payload.get("meta") self.detail: Optional[str] = payload.get("detail") - self.scim_type: Optional[str] = payload.get("scimType") + self.scim_type: Optional["UserInstance.str"] = payload.get("scimType") self.status: Optional[str] = payload.get("status") self.code: Optional[int] = payload.get("code") self.more_info: Optional[str] = payload.get("moreInfo") @@ -198,6 +242,7 @@ def __init__( "organization_sid": organization_sid, "id": id or self.id, } + self._context: Optional[UserContext] = None @property @@ -234,6 +279,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -252,6 +315,60 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + return self._proxy.patch( + scim_patch_request=scim_patch_request, + if_match=if_match, + ) + + async def patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + return await self._proxy.patch_async( + scim_patch_request=scim_patch_request, + if_match=if_match, + ) + def update( self, scim_user: ScimUser, if_match: Union[str, object] = values.unset ) -> "UserInstance": @@ -284,6 +401,38 @@ async def update_async( if_match=if_match, ) + def update_with_http_info( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + scim_user=scim_user, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + scim_user=scim_user, + if_match=if_match, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -326,16 +475,16 @@ class ScimMeta(object): def __init__(self, payload: Dict[str, Any]): - self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_type: Optional[str] = payload.get("resourceType") self.created: Optional[datetime] = payload.get("created") - self.last_modified: Optional[datetime] = payload.get("last_modified") + self.last_modified: Optional[datetime] = payload.get("lastModified") self.version: Optional[str] = payload.get("version") def to_dict(self): return { - "resource_type": self.resource_type, + "resourceType": self.resource_type, "created": self.created, - "last_modified": self.last_modified, + "lastModified": self.last_modified, "version": self.version, } @@ -347,13 +496,56 @@ class ScimName(object): def __init__(self, payload: Dict[str, Any]): - self.given_name: Optional[str] = payload.get("given_name") - self.family_name: Optional[str] = payload.get("family_name") + self.given_name: Optional[str] = payload.get("givenName") + self.family_name: Optional[str] = payload.get("familyName") + + def to_dict(self): + return { + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) def to_dict(self): return { - "given_name": self.given_name, - "family_name": self.family_name, + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), } class ScimUser(object): @@ -379,9 +571,9 @@ class ScimUser(object): def __init__(self, payload: Dict[str, Any]): self.id: Optional[str] = payload.get("id") - self.external_id: Optional[str] = payload.get("external_id") - self.user_name: Optional[str] = payload.get("user_name") - self.display_name: Optional[str] = payload.get("display_name") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") self.name: Optional[UserList.ScimName] = payload.get("name") self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( "emails" @@ -392,10 +584,10 @@ def __init__(self, payload: Dict[str, Any]): self.schemas: Optional[List[str]] = payload.get("schemas") self.meta: Optional[UserList.ScimMeta] = payload.get("meta") self.detail: Optional[str] = payload.get("detail") - self.scim_type: Optional[str] = payload.get("scim_type") + self.scim_type: Optional["UserInstance.str"] = payload.get("scimType") self.status: Optional[str] = payload.get("status") self.code: Optional[int] = payload.get("code") - self.more_info: Optional[str] = payload.get("more_info") + self.more_info: Optional[str] = payload.get("moreInfo") def to_dict(self): return { @@ -438,6 +630,22 @@ def __init__(self, version: Version, organization_sid: str, id: str): } self._uri = "/{organization_sid}/scim/Users/{id}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -445,12 +653,34 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) headers["Accept"] = "application/scim+json" - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -459,13 +689,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({}) headers["Accept"] = "application/scim+json" - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> UserInstance: @@ -475,36 +725,54 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) - headers = values.of({}) - - headers["Accept"] = "application/scim+json" + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - return UserInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = UserInstance( self._version, payload, organization_sid=self._solution["organization_sid"], id=self._solution["id"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - async def fetch_async(self) -> UserInstance: + async def _fetch_async(self) -> tuple: """ - Asynchronous coroutine to fetch the UserInstance + Internal async helper for fetch operation - - :returns: The fetched UserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/scim+json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + payload, _, _ = await self._fetch_async() return UserInstance( self._version, payload, @@ -512,18 +780,34 @@ async def fetch_async(self) -> UserInstance: id=self._solution["id"], ) - def update( - self, scim_user: ScimUser, if_match: Union[str, object] = values.unset - ) -> UserInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the UserInstance + Asynchronous coroutine to fetch the UserInstance and return response metadata - :param scim_user: - :param if_match: - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers """ - data = scim_user.to_dict() + payload, status_code, headers = await self._fetch_async() + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_patch_request.to_dict() headers = values.of({}) @@ -538,10 +822,26 @@ def update( headers["Accept"] = "application/scim+json" - payload = self._version.update( - method="PUT", uri=self._uri, data=data, headers=headers + return self._version.patch_with_response_info( + method="PATCH", uri=self._uri, data=data, headers=headers ) + def patch( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + payload, _, _ = self._patch( + scim_patch_request=scim_patch_request, if_match=if_match + ) return UserInstance( self._version, payload, @@ -549,18 +849,42 @@ def update( id=self._solution["id"], ) - async def update_async( - self, scim_user: ScimUser, if_match: Union[str, object] = values.unset - ) -> UserInstance: + def patch_with_http_info( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to update the UserInstance + Patch the UserInstance and return response metadata - :param scim_user: + :param scim_patch_request: :param if_match: - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers """ - data = scim_user.to_dict() + payload, status_code, headers = self._patch( + scim_patch_request=scim_patch_request, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_patch_request.to_dict() headers = values.of({}) @@ -575,10 +899,26 @@ async def update_async( headers["Accept"] = "application/scim+json" - payload = await self._version.update_async( - method="PUT", uri=self._uri, data=data, headers=headers + return await self._version.patch_with_response_info_async( + method="PATCH", uri=self._uri, data=data, headers=headers ) + async def patch_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to patch the UserInstance + + :param scim_patch_request: + :param if_match: + + :returns: The patched UserInstance + """ + payload, _, _ = await self._patch_async( + scim_patch_request=scim_patch_request, if_match=if_match + ) return UserInstance( self._version, payload, @@ -586,35 +926,198 @@ async def update_async( id=self._solution["id"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + async def patch_with_http_info_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.PreviewIam.Versionless.UserContext {}>".format(context) - - -class UserPage(Page): + Asynchronous coroutine to patch the UserInstance and return response metadata - def get_instance(self, payload: Dict[str, Any]) -> UserInstance: - """ - Build an instance of UserInstance + :param scim_patch_request: + :param if_match: - :param payload: Payload response from the API + :returns: ApiResponse with instance, status code, and headers """ - return UserInstance( - self._version, payload, organization_sid=self._solution["organization_sid"] + payload, status_code, headers = await self._patch_async( + scim_patch_request=scim_patch_request, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def __repr__(self) -> str: + def _update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal helper for update operation - :returns: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - return "<Twilio.PreviewIam.Versionless.UserPage>" + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + payload, _, _ = self._update(scim_user=scim_user, if_match=if_match) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def update_with_http_info( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the UserInstance and return response metadata + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + scim_user=scim_user, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async(scim_user=scim_user, if_match=if_match) + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def update_with_http_info_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata + + :param scim_user: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + scim_user=scim_user, if_match=if_match + ) + instance = UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.UserPage>" class UserList(ListResource): @@ -649,16 +1152,16 @@ class ScimMeta(object): def __init__(self, payload: Dict[str, Any]): - self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_type: Optional[str] = payload.get("resourceType") self.created: Optional[datetime] = payload.get("created") - self.last_modified: Optional[datetime] = payload.get("last_modified") + self.last_modified: Optional[datetime] = payload.get("lastModified") self.version: Optional[str] = payload.get("version") def to_dict(self): return { - "resource_type": self.resource_type, + "resourceType": self.resource_type, "created": self.created, - "last_modified": self.last_modified, + "lastModified": self.last_modified, "version": self.version, } @@ -670,13 +1173,56 @@ class ScimName(object): def __init__(self, payload: Dict[str, Any]): - self.given_name: Optional[str] = payload.get("given_name") - self.family_name: Optional[str] = payload.get("family_name") + self.given_name: Optional[str] = payload.get("givenName") + self.family_name: Optional[str] = payload.get("familyName") def to_dict(self): return { - "given_name": self.given_name, - "family_name": self.family_name, + "givenName": self.given_name, + "familyName": self.family_name, + } + + class ScimPatchOperation(object): + """ + :ivar op: The operation to perform + :ivar path: + :ivar value: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.op: Optional[str] = payload.get("op") + self.path: Optional[str] = payload.get("path") + self.value: Optional[Dict[str, object]] = payload.get("value") + + def to_dict(self): + return { + "op": self.op, + "path": self.path, + "value": self.value, + } + + class ScimPatchRequest(object): + """ + :ivar schemas: + :ivar operations: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.schemas: Optional[List[str]] = payload.get("schemas") + self.operations: Optional[List[UserList.ScimPatchOperation]] = payload.get( + "Operations" + ) + + def to_dict(self): + return { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), } class ScimUser(object): @@ -702,9 +1248,9 @@ class ScimUser(object): def __init__(self, payload: Dict[str, Any]): self.id: Optional[str] = payload.get("id") - self.external_id: Optional[str] = payload.get("external_id") - self.user_name: Optional[str] = payload.get("user_name") - self.display_name: Optional[str] = payload.get("display_name") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") self.name: Optional[UserList.ScimName] = payload.get("name") self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( "emails" @@ -715,10 +1261,10 @@ def __init__(self, payload: Dict[str, Any]): self.schemas: Optional[List[str]] = payload.get("schemas") self.meta: Optional[UserList.ScimMeta] = payload.get("meta") self.detail: Optional[str] = payload.get("detail") - self.scim_type: Optional[str] = payload.get("scim_type") + self.scim_type: Optional["UserInstance.str"] = payload.get("scimType") self.status: Optional[str] = payload.get("status") self.code: Optional[int] = payload.get("code") - self.more_info: Optional[str] = payload.get("more_info") + self.more_info: Optional[str] = payload.get("moreInfo") def to_dict(self): return { @@ -760,13 +1306,12 @@ def __init__(self, version: Version, organization_sid: str): } self._uri = "/{organization_sid}/scim/Users".format(**self._solution) - def create(self, scim_user: ScimUser) -> UserInstance: + def _create(self, scim_user: ScimUser) -> tuple: """ - Create the UserInstance - - :param scim_user: + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = scim_user.to_dict() @@ -778,21 +1323,43 @@ def create(self, scim_user: ScimUser) -> UserInstance: headers["Accept"] = "application/scim+json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, scim_user: ScimUser) -> UserInstance: + """ + Create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + payload, _, _ = self._create(scim_user=scim_user) return UserInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) - async def create_async(self, scim_user: ScimUser) -> UserInstance: + def create_with_http_info(self, scim_user: ScimUser) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param scim_user: - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(scim_user=scim_user) + instance = UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, scim_user: ScimUser) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = scim_user.to_dict() @@ -804,14 +1371,37 @@ async def create_async(self, scim_user: ScimUser) -> UserInstance: headers["Accept"] = "application/scim+json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, scim_user: ScimUser) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async(scim_user=scim_user) return UserInstance( self._version, payload, organization_sid=self._solution["organization_sid"] ) + async def create_with_http_info_async(self, scim_user: ScimUser) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param scim_user: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(scim_user=scim_user) + instance = UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, filter: Union[str, object] = values.unset, @@ -866,6 +1456,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserInstance and returns headers from first page + + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + filter=filter, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserInstance and returns headers from first page + + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + filter=filter, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, filter: Union[str, object] = values.unset, @@ -887,6 +1533,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( filter=filter, @@ -916,6 +1563,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -925,6 +1573,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserInstance and returns headers from first page + + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + filter=filter, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserInstance and returns headers from first page + + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, filter: Union[str, object] = values.unset, @@ -959,7 +1663,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -995,7 +1699,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UserPage, status code, and headers + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UserPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UserPage: """ @@ -1007,7 +1787,7 @@ def get_page(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UserPage: """ @@ -1019,7 +1799,7 @@ async def get_page_async(self, target_url: str) -> UserPage: :returns: Page of UserInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserPage(self._version, response, self._solution) + return UserPage(self._version, response, solution=self._solution) def get(self, id: str) -> UserContext: """ diff --git a/twilio/rest/pricing/v1/messaging/country.py b/twilio/rest/pricing/v1/messaging/country.py index 49360cd85c..ecb387919d 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -86,6 +88,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -113,48 +133,96 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Messaging/Countries/{iso_country}".format(**self._solution) - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance - + Internal helper for fetch operation - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -173,6 +241,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -247,6 +316,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -266,6 +385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -292,6 +412,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -300,6 +421,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -366,6 +537,76 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/pricing/v1/phone_number/country.py b/twilio/rest/pricing/v1/phone_number/country.py index 2d11cd1c3e..7775696a6d 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -84,6 +86,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -111,48 +131,96 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/PhoneNumbers/Countries/{iso_country}".format(**self._solution) - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance - + Internal helper for fetch operation - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +239,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -245,6 +314,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -264,6 +383,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -290,6 +410,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -298,6 +419,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -364,6 +535,76 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/pricing/v1/voice/country.py b/twilio/rest/pricing/v1/voice/country.py index 7fb0da883a..600488ab44 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,48 +135,96 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance - + Internal helper for fetch operation - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -175,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -249,6 +318,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -268,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -294,6 +414,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -302,6 +423,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -368,6 +539,76 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/pricing/v1/voice/number.py b/twilio/rest/pricing/v1/voice/number.py index 5bff8cd5d6..5dab5e2dd0 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ def __init__( self._solution = { "number": number or self.number, } + self._context: Optional[NumberContext] = None @property @@ -82,6 +84,24 @@ async def fetch_async(self) -> "NumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -109,48 +129,96 @@ def __init__(self, version: Version, number: str): } self._uri = "/Voice/Numbers/{number}".format(**self._solution) - def fetch(self) -> NumberInstance: + def _fetch(self) -> tuple: """ - Fetch the NumberInstance + Internal helper for fetch operation - - :returns: The fetched NumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> NumberInstance: + """ + Fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + payload, _, _ = self._fetch() return NumberInstance( self._version, payload, number=self._solution["number"], ) - async def fetch_async(self) -> NumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NumberInstance + Fetch the NumberInstance and return response metadata - :returns: The fetched NumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + payload, _, _ = await self._fetch_async() return NumberInstance( self._version, payload, number=self._solution["number"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/pricing/v2/country.py b/twilio/rest/pricing/v2/country.py index 30672235a8..94cdd8a272 100644 --- a/twilio/rest/pricing/v2/country.py +++ b/twilio/rest/pricing/v2/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,48 +135,96 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Trunking/Countries/{iso_country}".format(**self._solution) - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance - + Internal helper for fetch operation - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -175,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -249,6 +318,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -268,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -294,6 +414,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -302,6 +423,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -368,6 +539,76 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/pricing/v2/number.py b/twilio/rest/pricing/v2/number.py index 1dead39347..eddd2b6ef5 100644 --- a/twilio/rest/pricing/v2/number.py +++ b/twilio/rest/pricing/v2/number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -101,6 +103,34 @@ async def fetch_async( origination_number=origination_number, ) + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + origination_number=origination_number, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -128,18 +158,15 @@ def __init__(self, version: Version, destination_number: str): } self._uri = "/Trunking/Numbers/{destination_number}".format(**self._solution) - def fetch( - self, origination_number: Union[str, object] = values.unset - ) -> NumberInstance: + def _fetch(self, origination_number: Union[str, object] = values.unset) -> tuple: """ - Fetch the NumberInstance + Internal helper for fetch operation - :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. - - :returns: The fetched NumberInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "OriginationNumber": origination_number, } @@ -149,28 +176,58 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + payload, _, _ = self._fetch(origination_number=origination_number) return NumberInstance( self._version, payload, destination_number=self._solution["destination_number"], ) - async def fetch_async( + def fetch_with_http_info( self, origination_number: Union[str, object] = values.unset - ) -> NumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the NumberInstance + Fetch the NumberInstance and return response metadata :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. - :returns: The fetched NumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "OriginationNumber": origination_number, } @@ -180,16 +237,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + payload, _, _ = await self._fetch_async(origination_number=origination_number) return NumberInstance( self._version, payload, destination_number=self._solution["destination_number"], ) + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance and return response metadata + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/pricing/v2/voice/country.py b/twilio/rest/pricing/v2/voice/country.py index 997f368462..303e8d8522 100644 --- a/twilio/rest/pricing/v2/voice/country.py +++ b/twilio/rest/pricing/v2/voice/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,48 +135,96 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance - + Internal helper for fetch operation - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_country=self._solution["iso_country"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -175,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -249,6 +318,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -268,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -294,6 +414,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -302,6 +423,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -368,6 +539,76 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/pricing/v2/voice/number.py b/twilio/rest/pricing/v2/voice/number.py index 97a3a526ff..516e6f4cb4 100644 --- a/twilio/rest/pricing/v2/voice/number.py +++ b/twilio/rest/pricing/v2/voice/number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -99,6 +101,34 @@ async def fetch_async( origination_number=origination_number, ) + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + origination_number=origination_number, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,18 +156,15 @@ def __init__(self, version: Version, destination_number: str): } self._uri = "/Voice/Numbers/{destination_number}".format(**self._solution) - def fetch( - self, origination_number: Union[str, object] = values.unset - ) -> NumberInstance: + def _fetch(self, origination_number: Union[str, object] = values.unset) -> tuple: """ - Fetch the NumberInstance + Internal helper for fetch operation - :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. - - :returns: The fetched NumberInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "OriginationNumber": origination_number, } @@ -147,28 +174,58 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + payload, _, _ = self._fetch(origination_number=origination_number) return NumberInstance( self._version, payload, destination_number=self._solution["destination_number"], ) - async def fetch_async( + def fetch_with_http_info( self, origination_number: Union[str, object] = values.unset - ) -> NumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the NumberInstance + Fetch the NumberInstance and return response metadata :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. - :returns: The fetched NumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "OriginationNumber": origination_number, } @@ -178,16 +235,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + payload, _, _ = await self._fetch_async(origination_number=origination_number) return NumberInstance( self._version, payload, destination_number=self._solution["destination_number"], ) + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance and return response metadata + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + origination_number=origination_number + ) + instance = NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/proxy/v1/service/__init__.py b/twilio/rest/proxy/v1/service/__init__.py index ff1e7ed7d7..82b845dfb5 100644 --- a/twilio/rest/proxy/v1/service/__init__.py +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,7 +23,6 @@ from twilio.base.page import Page from twilio.rest.proxy.v1.service.phone_number import PhoneNumberList from twilio.rest.proxy.v1.service.session import SessionList -from twilio.rest.proxy.v1.service.short_code import ShortCodeList class ServiceInstance(InstanceResource): @@ -91,6 +91,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -126,6 +127,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -144,6 +163,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -220,6 +257,82 @@ async def update_async( chat_instance_sid=chat_instance_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -234,13 +347,6 @@ def sessions(self) -> SessionList: """ return self._proxy.sessions - @property - def short_codes(self) -> ShortCodeList: - """ - Access the short_codes - """ - return self._proxy.short_codes - def __repr__(self) -> str: """ Provide a friendly representation @@ -270,7 +376,20 @@ def __init__(self, version: Version, sid: str): self._phone_numbers: Optional[PhoneNumberList] = None self._sessions: Optional[SessionList] = None - self._short_codes: Optional[ShortCodeList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -279,10 +398,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -291,56 +432,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, default_ttl: Union[int, object] = values.unset, @@ -352,20 +547,12 @@ def update( intercept_callback_url: Union[str, object] = values.unset, out_of_session_callback_url: Union[str, object] = values.unset, chat_instance_sid: Union[str, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** - :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. - :param callback_url: The URL we should call when the interaction status changes. - :param geo_match_level: - :param number_selection_behavior: - :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. - :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. - :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -386,13 +573,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, default_ttl: Union[int, object] = values.unset, @@ -406,7 +591,7 @@ async def update_async( chat_instance_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. @@ -419,6 +604,77 @@ async def update_async( :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -438,47 +694,112 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def phone_numbers(self) -> PhoneNumberList: - """ - Access the phone_numbers + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList( - self._version, - self._solution["sid"], - ) - return self._phone_numbers + Asynchronous coroutine to update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def sessions(self) -> SessionList: + def phone_numbers(self) -> PhoneNumberList: """ - Access the sessions + Access the phone_numbers """ - if self._sessions is None: - self._sessions = SessionList( + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( self._version, self._solution["sid"], ) - return self._sessions + return self._phone_numbers @property - def short_codes(self) -> ShortCodeList: + def sessions(self) -> SessionList: """ - Access the short_codes + Access the sessions """ - if self._short_codes is None: - self._short_codes = ShortCodeList( + if self._sessions is None: + self._sessions = SessionList( self._version, self._solution["sid"], ) - return self._short_codes + return self._sessions def __repr__(self) -> str: """ @@ -498,6 +819,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -522,7 +844,7 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, unique_name: str, default_ttl: Union[int, object] = values.unset, @@ -534,20 +856,12 @@ def create( intercept_callback_url: Union[str, object] = values.unset, out_of_session_callback_url: Union[str, object] = values.unset, chat_instance_sid: Union[str, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** - :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. - :param callback_url: The URL we should call when the interaction status changes. - :param geo_match_level: - :param number_selection_behavior: - :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. - :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. - :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -568,13 +882,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, default_ttl: Union[int, object] = values.unset, @@ -588,7 +900,7 @@ async def create_async( chat_instance_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. @@ -601,6 +913,77 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -620,12 +1003,89 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -676,6 +1136,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -695,6 +1205,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -721,6 +1232,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -729,6 +1241,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -795,6 +1357,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/proxy/v1/service/phone_number.py b/twilio/rest/proxy/v1/service/phone_number.py index 3c8517cedd..8d206f2e06 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -104,6 +106,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -122,6 +142,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, is_reserved: Union[bool, object] = values.unset ) -> "PhoneNumberInstance": @@ -150,6 +188,34 @@ async def update_async( is_reserved=is_reserved, ) + def update_with_http_info( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + is_reserved=is_reserved, + ) + + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + is_reserved=is_reserved, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +247,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -188,10 +268,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -200,27 +302,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PhoneNumberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PhoneNumberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() return PhoneNumberInstance( self._version, payload, @@ -228,22 +346,46 @@ def fetch(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> PhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return PhoneNumberInstance( self._version, payload, @@ -251,15 +393,28 @@ async def fetch_async(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) - def update( - self, is_reserved: Union[bool, object] = values.unset - ) -> PhoneNumberInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the PhoneNumberInstance + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata - :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The updated PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, is_reserved: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -273,10 +428,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = self._update(is_reserved=is_reserved) return PhoneNumberInstance( self._version, payload, @@ -284,15 +450,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, is_reserved: Union[bool, object] = values.unset - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PhoneNumberInstance + Update the PhoneNumberInstance and return response metadata :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The updated PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(is_reserved=is_reserved) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -306,10 +490,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = await self._update_async(is_reserved=is_reserved) return PhoneNumberInstance( self._version, payload, @@ -317,6 +512,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -335,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -366,20 +583,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - def create( + def _create( self, sid: Union[str, object] = values.unset, phone_number: Union[str, object] = values.unset, is_reserved: Union[bool, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> tuple: """ - Create the PhoneNumberInstance - - :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. - :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + Internal helper for create operation - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -395,28 +609,66 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, sid: Union[str, object] = values.unset, phone_number: Union[str, object] = values.unset, is_reserved: Union[bool, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronously create the PhoneNumberInstance + Create the PhoneNumberInstance and return response metadata :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The created PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -432,14 +684,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PhoneNumberInstance and return response metadata + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -490,6 +783,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -509,6 +852,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -535,6 +879,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -543,6 +888,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -574,7 +969,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -607,7 +1002,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PhoneNumberPage: """ @@ -619,7 +1084,7 @@ def get_page(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ @@ -631,7 +1096,7 @@ async def get_page_async(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PhoneNumberContext: """ diff --git a/twilio/rest/proxy/v1/service/session/__init__.py b/twilio/rest/proxy/v1/service/session/__init__.py index 839db075c3..ba7ee376b3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -99,6 +100,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SessionContext] = None @property @@ -135,6 +137,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SessionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SessionInstance": """ Fetch the SessionInstance @@ -153,6 +173,24 @@ async def fetch_async(self) -> "SessionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, date_expiry: Union[datetime, object] = values.unset, @@ -195,6 +233,48 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the SessionInstance with HTTP info + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + async def update_with_http_info_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SessionInstance with HTTP info + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + @property def interactions(self) -> InteractionList: """ @@ -241,6 +321,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._interactions: Optional[InteractionList] = None self._participants: Optional[ParticipantList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SessionInstance @@ -248,10 +342,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SessionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -260,27 +376,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SessionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SessionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SessionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + :returns: The fetched SessionInstance + """ + payload, _, _ = self._fetch() return SessionInstance( self._version, payload, @@ -288,22 +420,46 @@ def fetch(self) -> SessionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SessionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SessionInstance + Fetch the SessionInstance and return response metadata - :returns: The fetched SessionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = await self._fetch_async() return SessionInstance( self._version, payload, @@ -311,20 +467,33 @@ async def fetch_async(self) -> SessionInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, date_expiry: Union[datetime, object] = values.unset, ttl: Union[int, object] = values.unset, status: Union["SessionInstance.Status", object] = values.unset, - ) -> SessionInstance: + ) -> tuple: """ - Update the SessionInstance + Internal helper for update operation - :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. - :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. - :param status: - - :returns: The updated SessionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -340,10 +509,26 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + payload, _, _ = self._update(date_expiry=date_expiry, ttl=ttl, status=status) return SessionInstance( self._version, payload, @@ -351,20 +536,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, date_expiry: Union[datetime, object] = values.unset, ttl: Union[int, object] = values.unset, status: Union["SessionInstance.Status", object] = values.unset, - ) -> SessionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SessionInstance + Update the SessionInstance and return response metadata :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. :param status: - :returns: The updated SessionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + date_expiry=date_expiry, ttl=ttl, status=status + ) + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -380,10 +588,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + payload, _, _ = await self._update_async( + date_expiry=date_expiry, ttl=ttl, status=status + ) return SessionInstance( self._version, payload, @@ -391,6 +617,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SessionInstance and return response metadata + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + date_expiry=date_expiry, ttl=ttl, status=status + ) + instance = SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def interactions(self) -> InteractionList: """ @@ -435,6 +687,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: :param payload: Payload response from the API """ + return SessionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -466,7 +719,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Sessions".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, date_expiry: Union[datetime, object] = values.unset, @@ -474,18 +727,12 @@ def create( mode: Union["SessionInstance.Mode", object] = values.unset, status: Union["SessionInstance.Status", object] = values.unset, participants: Union[List[object], object] = values.unset, - ) -> SessionInstance: + ) -> tuple: """ - Create the SessionInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** - :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. - :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. - :param mode: - :param status: - :param participants: The Participant objects to include in the new session. + Internal helper for create operation - :returns: The created SessionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -506,15 +753,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) return SessionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, date_expiry: Union[datetime, object] = values.unset, @@ -522,9 +798,9 @@ async def create_async( mode: Union["SessionInstance.Mode", object] = values.unset, status: Union["SessionInstance.Status", object] = values.unset, participants: Union[List[object], object] = values.unset, - ) -> SessionInstance: + ) -> ApiResponse: """ - Asynchronously create the SessionInstance + Create the SessionInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. @@ -533,7 +809,35 @@ async def create_async( :param status: :param participants: The Participant objects to include in the new session. - :returns: The created SessionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + instance = SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -554,14 +858,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Asynchronously create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) return SessionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SessionInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + instance = SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -612,6 +979,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -631,6 +1048,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -657,6 +1075,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -665,6 +1084,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -696,7 +1165,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SessionPage(self._version, response, self._solution) + return SessionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -729,7 +1198,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SessionPage(self._version, response, self._solution) + return SessionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SessionPage: """ @@ -741,7 +1280,7 @@ def get_page(self, target_url: str) -> SessionPage: :returns: Page of SessionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SessionPage(self._version, response, self._solution) + return SessionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SessionPage: """ @@ -753,7 +1292,7 @@ async def get_page_async(self, target_url: str) -> SessionPage: :returns: Page of SessionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SessionPage(self._version, response, self._solution) + return SessionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SessionContext: """ diff --git a/twilio/rest/proxy/v1/service/session/interaction.py b/twilio/rest/proxy/v1/service/session/interaction.py index 7eeccda5bc..abf834776c 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -123,6 +124,7 @@ def __init__( "session_sid": session_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionContext] = None @property @@ -160,6 +162,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InteractionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InteractionInstance": """ Fetch the InteractionInstance @@ -178,6 +198,24 @@ async def fetch_async(self) -> "InteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -213,6 +251,20 @@ def __init__(self, version: Version, service_sid: str, session_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InteractionInstance @@ -220,10 +272,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InteractionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -232,27 +306,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> InteractionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the InteractionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched InteractionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + payload, _, _ = self._fetch() return InteractionInstance( self._version, payload, @@ -261,22 +351,47 @@ def fetch(self) -> InteractionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> InteractionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the InteractionInstance + Fetch the InteractionInstance and return response metadata - :returns: The fetched InteractionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + payload, _, _ = await self._fetch_async() return InteractionInstance( self._version, payload, @@ -285,6 +400,23 @@ async def fetch_async(self) -> InteractionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -303,6 +435,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: :param payload: Payload response from the API """ + return InteractionInstance( self._version, payload, @@ -393,6 +526,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -412,6 +595,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -438,6 +622,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -446,6 +631,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -477,7 +712,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionPage(self._version, response, self._solution) + return InteractionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -510,7 +745,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return InteractionPage(self._version, response, self._solution) + return InteractionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InteractionPage: """ @@ -522,7 +827,7 @@ def get_page(self, target_url: str) -> InteractionPage: :returns: Page of InteractionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return InteractionPage(self._version, response, self._solution) + return InteractionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> InteractionPage: """ @@ -534,7 +839,7 @@ async def get_page_async(self, target_url: str) -> InteractionPage: :returns: Page of InteractionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InteractionPage(self._version, response, self._solution) + return InteractionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> InteractionContext: """ diff --git a/twilio/rest/proxy/v1/service/session/participant/__init__.py b/twilio/rest/proxy/v1/service/session/participant/__init__.py index 7ad20fcffb..90c3af7080 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "session_sid": session_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def message_interactions(self) -> MessageInteractionList: """ @@ -176,6 +214,20 @@ def __init__(self, version: Version, service_sid: str, session_sid: str, sid: st self._message_interactions: Optional[MessageInteractionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ParticipantInstance @@ -183,10 +235,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -195,27 +269,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ParticipantInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ParticipantInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -224,22 +314,47 @@ def fetch(self) -> ParticipantInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -248,6 +363,23 @@ async def fetch_async(self) -> ParticipantInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def message_interactions(self) -> MessageInteractionList: """ @@ -280,6 +412,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -320,22 +453,18 @@ def __init__(self, version: Version, service_sid: str, session_sid: str): ) ) - def create( + def _create( self, identifier: str, friendly_name: Union[str, object] = values.unset, proxy_identifier: Union[str, object] = values.unset, proxy_identifier_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance + Internal helper for create operation - :param identifier: The phone number of the Participant. - :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** - :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. - :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. - - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -352,10 +481,33 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = self._create( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) return ParticipantInstance( self._version, payload, @@ -363,22 +515,49 @@ def create( session_sid=self._solution["session_sid"], ) - async def create_async( + def create_with_http_info( self, identifier: str, friendly_name: Union[str, object] = values.unset, proxy_identifier: Union[str, object] = values.unset, proxy_identifier_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance and return response metadata :param identifier: The phone number of the Participant. :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -395,10 +574,33 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + payload, _, _ = await self._create_async( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) return ParticipantInstance( self._version, payload, @@ -406,6 +608,37 @@ async def create_async( session_sid=self._solution["session_sid"], ) + async def create_with_http_info_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -456,6 +689,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -475,6 +758,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -501,6 +785,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -509,6 +794,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -540,7 +875,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -573,7 +908,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -585,7 +990,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -597,7 +1002,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py index 4ffe67965b..49a2c998c4 100644 --- a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py +++ b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -127,6 +128,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[MessageInteractionContext] = None @property @@ -165,6 +167,24 @@ async def fetch_async(self) -> "MessageInteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,20 +227,30 @@ def __init__( **self._solution ) - def fetch(self) -> MessageInteractionInstance: + def _fetch(self) -> tuple: """ - Fetch the MessageInteractionInstance - + Internal helper for fetch operation - :returns: The fetched MessageInteractionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInteractionInstance: + """ + Fetch the MessageInteractionInstance + + :returns: The fetched MessageInteractionInstance + """ + payload, _, _ = self._fetch() return MessageInteractionInstance( self._version, payload, @@ -230,22 +260,48 @@ def fetch(self) -> MessageInteractionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> MessageInteractionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessageInteractionInstance + Fetch the MessageInteractionInstance and return response metadata - :returns: The fetched MessageInteractionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessageInteractionInstance: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + payload, _, _ = await self._fetch_async() return MessageInteractionInstance( self._version, payload, @@ -255,6 +311,24 @@ async def fetch_async(self) -> MessageInteractionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -273,6 +347,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: :param payload: Payload response from the API """ + return MessageInteractionInstance( self._version, payload, @@ -316,18 +391,16 @@ def __init__( **self._solution ) - def create( + def _create( self, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, - ) -> MessageInteractionInstance: + ) -> tuple: """ - Create the MessageInteractionInstance - - :param body: The message to send to the participant - :param media_url: Reserved. Not currently supported. + Internal helper for create operation - :returns: The created MessageInteractionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -342,10 +415,24 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + payload, _, _ = self._create(body=body, media_url=media_url) return MessageInteractionInstance( self._version, payload, @@ -354,18 +441,39 @@ def create( participant_sid=self._solution["participant_sid"], ) - async def create_async( + def create_with_http_info( self, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, - ) -> MessageInteractionInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInteractionInstance + Create the MessageInteractionInstance and return response metadata :param body: The message to send to the participant :param media_url: Reserved. Not currently supported. - :returns: The created MessageInteractionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body, media_url=media_url) + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -380,10 +488,24 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Asynchronously create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + payload, _, _ = await self._create_async(body=body, media_url=media_url) return MessageInteractionInstance( self._version, payload, @@ -392,6 +514,31 @@ async def create_async( participant_sid=self._solution["participant_sid"], ) + async def create_with_http_info_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInteractionInstance and return response metadata + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, media_url=media_url + ) + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -442,6 +589,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -461,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -487,6 +685,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -495,6 +694,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessageInteractionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -526,7 +775,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessageInteractionPage(self._version, response, self._solution) + return MessageInteractionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -559,7 +808,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessageInteractionPage(self._version, response, self._solution) + return MessageInteractionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessageInteractionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessageInteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessageInteractionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessageInteractionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessageInteractionPage: """ @@ -571,7 +890,7 @@ def get_page(self, target_url: str) -> MessageInteractionPage: :returns: Page of MessageInteractionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessageInteractionPage(self._version, response, self._solution) + return MessageInteractionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> MessageInteractionPage: """ @@ -583,7 +902,7 @@ async def get_page_async(self, target_url: str) -> MessageInteractionPage: :returns: Page of MessageInteractionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessageInteractionPage(self._version, response, self._solution) + return MessageInteractionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageInteractionContext: """ diff --git a/twilio/rest/proxy/v1/service/short_code.py b/twilio/rest/proxy/v1/service/short_code.py deleted file mode 100644 index df71d4bdd5..0000000000 --- a/twilio/rest/proxy/v1/service/short_code.py +++ /dev/null @@ -1,638 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Proxy - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class ShortCodeInstance(InstanceResource): - """ - :ivar sid: The unique string that we created to identify the ShortCode resource. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. - :ivar service_sid: The SID of the ShortCode resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. - :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. - :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. - :ivar short_code: The short code's number. - :ivar iso_country: The ISO Country Code for the short code. - :ivar capabilities: - :ivar url: The absolute URL of the ShortCode resource. - :ivar is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.short_code: Optional[str] = payload.get("short_code") - self.iso_country: Optional[str] = payload.get("iso_country") - self.capabilities: Optional[str] = payload.get("capabilities") - self.url: Optional[str] = payload.get("url") - self.is_reserved: Optional[bool] = payload.get("is_reserved") - - self._solution = { - "service_sid": service_sid, - "sid": sid or self.sid, - } - self._context: Optional[ShortCodeContext] = None - - @property - def _proxy(self) -> "ShortCodeContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ShortCodeContext for this ShortCodeInstance - """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ShortCodeInstance": - """ - Fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ShortCodeInstance": - """ - Asynchronous coroutine to fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - return await self._proxy.fetch_async() - - def update( - self, is_reserved: Union[bool, object] = values.unset - ) -> "ShortCodeInstance": - """ - Update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - return self._proxy.update( - is_reserved=is_reserved, - ) - - async def update_async( - self, is_reserved: Union[bool, object] = values.unset - ) -> "ShortCodeInstance": - """ - Asynchronous coroutine to update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - return await self._proxy.update_async( - is_reserved=is_reserved, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Proxy.V1.ShortCodeInstance {}>".format(context) - - -class ShortCodeContext(InstanceContext): - - def __init__(self, version: Version, service_sid: str, sid: str): - """ - Initialize the ShortCodeContext - - :param version: Version that contains the resource - :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to update. - :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - "sid": sid, - } - self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - - headers = values.of({}) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> ShortCodeInstance: - """ - Fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ShortCodeInstance: - """ - Asynchronous coroutine to fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - def update( - self, is_reserved: Union[bool, object] = values.unset - ) -> ShortCodeInstance: - """ - Update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - - data = values.of( - { - "IsReserved": serialize.boolean_to_string(is_reserved), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, is_reserved: Union[bool, object] = values.unset - ) -> ShortCodeInstance: - """ - Asynchronous coroutine to update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - - data = values.of( - { - "IsReserved": serialize.boolean_to_string(is_reserved), - } - ) - headers = values.of({}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Proxy.V1.ShortCodeContext {}>".format(context) - - -class ShortCodePage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: - """ - Build an instance of ShortCodeInstance - - :param payload: Payload response from the API - """ - return ShortCodeInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Proxy.V1.ShortCodePage>" - - -class ShortCodeList(ListResource): - - def __init__(self, version: Version, service_sid: str): - """ - Initialize the ShortCodeList - - :param version: Version that contains the resource - :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "service_sid": service_sid, - } - self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) - - def create(self, sid: str) -> ShortCodeInstance: - """ - Create the ShortCodeInstance - - :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - - data = values.of( - { - "Sid": sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async(self, sid: str) -> ShortCodeInstance: - """ - Asynchronously create the ShortCodeInstance - - :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - - data = values.of( - { - "Sid": sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ShortCodeInstance]: - """ - Streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[ShortCodeInstance]: - """ - Asynchronously streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ShortCodeInstance]: - """ - Lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ShortCodeInstance]: - """ - Asynchronously lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ShortCodePage: - """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ShortCodeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = self._version.page( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ShortCodePage(self._version, response, self._solution) - - async def page_async( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ShortCodePage: - """ - Asynchronously retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ShortCodeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Accept"] = "application/json" - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data, headers=headers - ) - return ShortCodePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> ShortCodePage: - """ - Retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ShortCodeInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return ShortCodePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> ShortCodePage: - """ - Asynchronously retrieve a specific page of ShortCodeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ShortCodeInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return ShortCodePage(self._version, response, self._solution) - - def get(self, sid: str) -> ShortCodeContext: - """ - Constructs a ShortCodeContext - - :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. - """ - return ShortCodeContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __call__(self, sid: str) -> ShortCodeContext: - """ - Constructs a ShortCodeContext - - :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. - """ - return ShortCodeContext( - self._version, service_sid=self._solution["service_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "<Twilio.Proxy.V1.ShortCodeList>" diff --git a/twilio/rest/routes/RoutesBase.py b/twilio/rest/routes/RoutesBase.py index a47d67f093..d156f7c44b 100644 --- a/twilio/rest/routes/RoutesBase.py +++ b/twilio/rest/routes/RoutesBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.routes.v2 import V2 +from twilio.rest.routes.v3 import V3 class RoutesBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://routes.twilio.com") self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v2(self) -> V2: @@ -36,6 +38,15 @@ def v2(self) -> V2: self._v2 = V2(self) return self._v2 + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Routes + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/routes/v2/phone_number.py b/twilio/rest/routes/v2/phone_number.py index 1b67509bb0..56b49fed77 100644 --- a/twilio/rest/routes/v2/phone_number.py +++ b/twilio/rest/routes/v2/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,60 +211,106 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - def fetch(self) -> PhoneNumberInstance: + def _fetch(self) -> tuple: """ - Fetch the PhoneNumberInstance - + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async(self) -> PhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> tuple: """ - Update the PhoneNumberInstance + Internal helper for update operation - :param voice_region: The Inbound Processing Region used for this phone number for voice - :param friendly_name: A human readable description of this resource, up to 64 characters. - - :returns: The updated PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -223,26 +325,61 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"] ) - async def update_async( + def update_with_http_info( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PhoneNumberInstance + Update the PhoneNumberInstance and return response metadata :param voice_region: The Inbound Processing Region used for this phone number for voice :param friendly_name: A human readable description of this resource, up to 64 characters. - :returns: The updated PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -257,14 +394,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) return PhoneNumberInstance( self._version, payload, phone_number=self._solution["phone_number"] ) + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/routes/v2/sip_domain.py b/twilio/rest/routes/v2/sip_domain.py index 2326a5dbc1..dd4445f3b6 100644 --- a/twilio/rest/routes/v2/sip_domain.py +++ b/twilio/rest/routes/v2/sip_domain.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sip_domain": sip_domain or self.sip_domain, } + self._context: Optional[SipDomainContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "SipDomainInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,60 +211,106 @@ def __init__(self, version: Version, sip_domain: str): } self._uri = "/SipDomains/{sip_domain}".format(**self._solution) - def fetch(self) -> SipDomainInstance: + def _fetch(self) -> tuple: """ - Fetch the SipDomainInstance - + Internal helper for fetch operation - :returns: The fetched SipDomainInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SipDomainInstance: + """ + Fetch the SipDomainInstance + + :returns: The fetched SipDomainInstance + """ + payload, _, _ = self._fetch() return SipDomainInstance( self._version, payload, sip_domain=self._solution["sip_domain"], ) - async def fetch_async(self) -> SipDomainInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SipDomainInstance + Fetch the SipDomainInstance and return response metadata - :returns: The fetched SipDomainInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SipDomainInstance: + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + payload, _, _ = await self._fetch_async() return SipDomainInstance( self._version, payload, sip_domain=self._solution["sip_domain"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SipDomainInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> SipDomainInstance: + ) -> tuple: """ - Update the SipDomainInstance + Internal helper for update operation - :param voice_region: - :param friendly_name: - - :returns: The updated SipDomainInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -223,26 +325,61 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) return SipDomainInstance( self._version, payload, sip_domain=self._solution["sip_domain"] ) - async def update_async( + def update_with_http_info( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> SipDomainInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SipDomainInstance + Update the SipDomainInstance and return response metadata :param voice_region: :param friendly_name: - :returns: The updated SipDomainInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -257,14 +394,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Asynchronous coroutine to update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) return SipDomainInstance( self._version, payload, sip_domain=self._solution["sip_domain"] ) + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SipDomainInstance and return response metadata + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/routes/v2/trunk.py b/twilio/rest/routes/v2/trunk.py index f783ce92ca..72d14c90bc 100644 --- a/twilio/rest/routes/v2/trunk.py +++ b/twilio/rest/routes/v2/trunk.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sip_trunk_domain": sip_trunk_domain or self.sip_trunk_domain, } + self._context: Optional[TrunkContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "TrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,60 +211,106 @@ def __init__(self, version: Version, sip_trunk_domain: str): } self._uri = "/Trunks/{sip_trunk_domain}".format(**self._solution) - def fetch(self) -> TrunkInstance: + def _fetch(self) -> tuple: """ - Fetch the TrunkInstance - + Internal helper for fetch operation - :returns: The fetched TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + :returns: The fetched TrunkInstance + """ + payload, _, _ = self._fetch() return TrunkInstance( self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"], ) - async def fetch_async(self) -> TrunkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrunkInstance + Fetch the TrunkInstance and return response metadata - :returns: The fetched TrunkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + payload, _, _ = await self._fetch_async() return TrunkInstance( self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> TrunkInstance: + ) -> tuple: """ - Update the TrunkInstance + Internal helper for update operation - :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice - :param friendly_name: A human readable description of this resource, up to 64 characters. - - :returns: The updated TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -223,26 +325,61 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + payload, _, _ = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) return TrunkInstance( self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] ) - async def update_async( + def update_with_http_info( self, voice_region: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> TrunkInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TrunkInstance + Update the TrunkInstance and return response metadata :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice :param friendly_name: A human readable description of this resource, up to 64 characters. - :returns: The updated TrunkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -257,14 +394,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) return TrunkInstance( self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] ) + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance and return response metadata + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name + ) + instance = TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/routes/v3/__init__.py b/twilio/rest/routes/v3/__init__.py new file mode 100644 index 0000000000..07d47c0f6f --- /dev/null +++ b/twilio/rest/routes/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.routes.v3.phone_number import PhoneNumberList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Routes + + :param domain: The Twilio.routes domain + """ + super().__init__(domain, "v3") + self._phone_numbers: Optional[PhoneNumberList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V3>" diff --git a/twilio/rest/routes/v3/phone_number.py b/twilio/rest/routes/v3/phone_number.py new file mode 100644 index 0000000000..c308460ccb --- /dev/null +++ b/twilio/rest/routes/v3/phone_number.py @@ -0,0 +1,521 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar phone_number: The phone number in E.164 format + :ivar url: The absolute URL of the resource. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A human readable description of the Inbound Processing Region assignments for this phone number, up to 64 characters. + :ivar voice_region: The Inbound Processing Region used for this phone number for voice. + :ivar messaging_region: The Inbound Processing Region used for this phone number for messaging. + :ivar date_created: The date that this phone number was assigned an Inbound Processing Region, given in ISO 8601 format. + :ivar date_updated: The date that the Inbound Processing Region was updated for this phone number, given in ISO 8601 format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phoneNumber") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("accountSid") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.voice_region: Optional[str] = payload.get("voiceRegion") + self.messaging_region: Optional[str] = payload.get("messagingRegion") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateCreated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("dateUpdated") + ) + + # Only set _solution if path params are provided (not None) + if phone_number is not None: + self._solution = { + "phone_number": phone_number, + } + + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return self._proxy.update( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V3.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number in E.164 format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "voiceRegion": voice_region, + "messagingRegion": messaging_region, + "friendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = self._update( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance and return response metadata + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "voiceRegion": voice_region, + "messagingRegion": messaging_region, + "friendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = await self._update_async( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + messaging_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param messaging_region: The Inbound Processing Region used for this phone number for messaging + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_region=voice_region, + messaging_region=messaging_region, + friendly_name=friendly_name, + ) + instance = PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V3.PhoneNumberContext {}>".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V3.PhoneNumberList>" diff --git a/twilio/rest/serverless/v1/service/__init__.py b/twilio/rest/serverless/v1/service/__init__.py index f6e4e5841e..2210d07e2e 100644 --- a/twilio/rest/serverless/v1/service/__init__.py +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -100,6 +102,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -118,6 +138,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, include_credentials: Union[bool, object] = values.unset, @@ -160,6 +198,48 @@ async def update_async( ui_editable=ui_editable, ) + def update_with_http_info( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + async def update_with_http_info_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + @property def assets(self) -> AssetList: """ @@ -220,6 +300,20 @@ def __init__(self, version: Version, sid: str): self._environments: Optional[EnvironmentList] = None self._functions: Optional[FunctionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -227,10 +321,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -239,69 +355,120 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, include_credentials: Union[bool, object] = values.unset, friendly_name: Union[str, object] = values.unset, ui_editable: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance + Internal helper for update operation - :param include_credentials: Whether to inject Account credentials into a function invocation context. - :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. - :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. - - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -317,20 +484,18 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, include_credentials: Union[bool, object] = values.unset, friendly_name: Union[str, object] = values.unset, ui_editable: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param include_credentials: Whether to inject Account credentials into a function invocation context. :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. @@ -338,6 +503,48 @@ async def update_async( :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -352,12 +559,55 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def assets(self) -> AssetList: """ @@ -424,6 +674,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -448,22 +699,18 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, unique_name: str, friendly_name: str, include_credentials: Union[bool, object] = values.unset, ui_editable: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. - :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. - :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. - :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -480,13 +727,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, friendly_name: str, @@ -494,7 +739,7 @@ async def create_async( ui_editable: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. @@ -503,6 +748,53 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -518,12 +810,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -574,6 +915,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -593,6 +984,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -619,6 +1011,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -627,6 +1020,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -693,6 +1136,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/serverless/v1/service/asset/__init__.py b/twilio/rest/serverless/v1/service/asset/__init__.py index de68b969be..8eae827c10 100644 --- a/twilio/rest/serverless/v1/service/asset/__init__.py +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AssetContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AssetInstance": """ Fetch the AssetInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "AssetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "AssetInstance": """ Update the AssetInstance @@ -139,6 +177,30 @@ async def update_async(self, friendly_name: str) -> "AssetInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the AssetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the AssetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def asset_versions(self) -> AssetVersionList: """ @@ -177,6 +239,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._asset_versions: Optional[AssetVersionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AssetInstance @@ -184,10 +260,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssetInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -196,27 +294,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> AssetInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the AssetInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched AssetInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AssetInstance: + """ + Fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + payload, _, _ = self._fetch() return AssetInstance( self._version, payload, @@ -224,22 +338,46 @@ def fetch(self) -> AssetInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AssetInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AssetInstance + Fetch the AssetInstance and return response metadata - :returns: The fetched AssetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AssetInstance: + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + payload, _, _ = await self._fetch_async() return AssetInstance( self._version, payload, @@ -247,13 +385,28 @@ async def fetch_async(self) -> AssetInstance: sid=self._solution["sid"], ) - def update(self, friendly_name: str) -> AssetInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the AssetInstance + Asynchronous coroutine to fetch the AssetInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. - :returns: The updated AssetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -267,10 +420,19 @@ def update(self, friendly_name: str) -> AssetInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: str) -> AssetInstance: + """ + Update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return AssetInstance( self._version, payload, @@ -278,13 +440,29 @@ def update(self, friendly_name: str) -> AssetInstance: sid=self._solution["sid"], ) - async def update_async(self, friendly_name: str) -> AssetInstance: + def update_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronous coroutine to update the AssetInstance + Update the AssetInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. - :returns: The updated AssetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +476,19 @@ async def update_async(self, friendly_name: str) -> AssetInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return AssetInstance( self._version, payload, @@ -309,6 +496,25 @@ async def update_async(self, friendly_name: str) -> AssetInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the AssetInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def asset_versions(self) -> AssetVersionList: """ @@ -340,6 +546,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: :param payload: Payload response from the API """ + return AssetInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -371,13 +578,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Assets".format(**self._solution) - def create(self, friendly_name: str) -> AssetInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the AssetInstance - - :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + Internal helper for create operation - :returns: The created AssetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -391,21 +597,43 @@ def create(self, friendly_name: str) -> AssetInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> AssetInstance: + """ + Create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return AssetInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, friendly_name: str) -> AssetInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the AssetInstance + Create the AssetInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. - :returns: The created AssetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -419,14 +647,39 @@ async def create_async(self, friendly_name: str) -> AssetInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronously create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return AssetInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the AssetInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -477,6 +730,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -496,6 +799,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -522,6 +826,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -530,6 +835,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -561,7 +916,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AssetPage(self._version, response, self._solution) + return AssetPage(self._version, response, solution=self._solution) async def page_async( self, @@ -594,7 +949,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AssetPage(self._version, response, self._solution) + return AssetPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssetPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssetPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AssetPage: """ @@ -606,7 +1031,7 @@ def get_page(self, target_url: str) -> AssetPage: :returns: Page of AssetInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AssetPage(self._version, response, self._solution) + return AssetPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AssetPage: """ @@ -618,7 +1043,7 @@ async def get_page_async(self, target_url: str) -> AssetPage: :returns: Page of AssetInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AssetPage(self._version, response, self._solution) + return AssetPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AssetContext: """ diff --git a/twilio/rest/serverless/v1/service/asset/asset_version.py b/twilio/rest/serverless/v1/service/asset/asset_version.py index 31f85d4c29..a8d50afe6b 100644 --- a/twilio/rest/serverless/v1/service/asset/asset_version.py +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "asset_sid": asset_sid, "sid": sid or self.sid, } + self._context: Optional[AssetVersionContext] = None @property @@ -105,6 +107,24 @@ async def fetch_async(self) -> "AssetVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,20 +158,30 @@ def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str) **self._solution ) - def fetch(self) -> AssetVersionInstance: + def _fetch(self) -> tuple: """ - Fetch the AssetVersionInstance - + Internal helper for fetch operation - :returns: The fetched AssetVersionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AssetVersionInstance: + """ + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + payload, _, _ = self._fetch() return AssetVersionInstance( self._version, payload, @@ -160,22 +190,47 @@ def fetch(self) -> AssetVersionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AssetVersionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AssetVersionInstance + Fetch the AssetVersionInstance and return response metadata - :returns: The fetched AssetVersionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AssetVersionInstance: + """ + Asynchronous coroutine to fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + payload, _, _ = await self._fetch_async() return AssetVersionInstance( self._version, payload, @@ -184,6 +239,23 @@ async def fetch_async(self) -> AssetVersionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetVersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -202,6 +274,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: :param payload: Payload response from the API """ + return AssetVersionInstance( self._version, payload, @@ -290,6 +363,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -309,6 +432,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -335,6 +459,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -343,6 +468,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssetVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -374,7 +549,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return AssetVersionPage(self._version, response, self._solution) + return AssetVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -407,7 +582,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return AssetVersionPage(self._version, response, self._solution) + return AssetVersionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssetVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssetVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssetVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AssetVersionPage: """ @@ -419,7 +664,7 @@ def get_page(self, target_url: str) -> AssetVersionPage: :returns: Page of AssetVersionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return AssetVersionPage(self._version, response, self._solution) + return AssetVersionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> AssetVersionPage: """ @@ -431,7 +676,7 @@ async def get_page_async(self, target_url: str) -> AssetVersionPage: :returns: Page of AssetVersionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AssetVersionPage(self._version, response, self._solution) + return AssetVersionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AssetVersionContext: """ diff --git a/twilio/rest/serverless/v1/service/build/__init__.py b/twilio/rest/serverless/v1/service/build/__init__.py index ddd59918b4..01c1856027 100644 --- a/twilio/rest/serverless/v1/service/build/__init__.py +++ b/twilio/rest/serverless/v1/service/build/__init__.py @@ -16,6 +16,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,9 +25,16 @@ from twilio.rest.serverless.v1.service.build.build_status import BuildStatusList + + + + + + class BuildInstance(InstanceResource): + class Runtime(object): NODE8 = "node8" NODE10 = "node10" @@ -34,6 +42,9 @@ class Runtime(object): NODE14 = "node14" NODE16 = "node16" NODE18 = "node18" + NODE20 = "node20" + NODE22 = "node22" + NODE24 = "node24" class Status(object): BUILDING = "building" @@ -55,7 +66,7 @@ class Status(object): :ivar links: """ - def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: Optional[str] = None): + def __init__(self, version: Version, payload:Dict[str, Any], service_sid: str, sid: Optional[str] = None): super().__init__(version) @@ -73,10 +84,13 @@ def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, self.links: Optional[Dict[str, object]] = payload.get("links") + self._solution = { "service_sid": service_sid, "sid": sid or self.sid, } + + self._context: Optional[BuildContext] = None @property @@ -108,6 +122,24 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BuildInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BuildInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() def fetch(self) -> "BuildInstance": @@ -127,6 +159,24 @@ async def fetch_async(self) -> "BuildInstance": :returns: The fetched BuildInstance """ return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() @property def build_status(self) -> BuildStatusList: @@ -146,6 +196,7 @@ def __repr__(self) -> str: class BuildContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildContext @@ -167,6 +218,21 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._build_status: Optional[BuildStatusList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + + headers = values.of({}) + + + + return self._version.delete_with_response_info(method='DELETE', uri=self._uri, headers=headers) + def delete(self) -> bool: """ Deletes the BuildInstance @@ -174,13 +240,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BuildInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method='DELETE', uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async(method='DELETE', uri=self._uri, headers=headers) async def delete_async(self) -> bool: """ @@ -189,30 +274,45 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BuildInstance and return response metadata + - headers = values.of({}) - - - - return await self._version.delete_async(method='DELETE', uri=self._uri, headers=headers) + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - def fetch(self) -> BuildInstance: + def _fetch(self) -> tuple: """ - Fetch the BuildInstance - + Internal helper for fetch operation - :returns: The fetched BuildInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + return self._version.fetch_with_response_info(method='GET', uri=self._uri, headers=headers) + + def fetch(self) -> BuildInstance: + """ + Fetch the BuildInstance + + :returns: The fetched BuildInstance + """ + payload, _, _ = self._fetch() return BuildInstance( self._version, payload, @@ -221,22 +321,48 @@ def fetch(self) -> BuildInstance: ) - async def fetch_async(self) -> BuildInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BuildInstance + Fetch the BuildInstance and return response metadata - :returns: The fetched BuildInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + headers["Accept"] = "application/json" - payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) + async def fetch_async(self) -> BuildInstance: + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + payload, _, _ = await self._fetch_async() return BuildInstance( self._version, payload, @@ -244,6 +370,23 @@ async def fetch_async(self) -> BuildInstance: sid=self._solution['sid'], ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property @@ -284,7 +427,9 @@ def get_instance(self, payload: Dict[str, Any]) -> BuildInstance: :param payload: Payload response from the API """ + return BuildInstance(self._version, payload, service_sid=self._solution["service_sid"]) + def __repr__(self) -> str: """ @@ -319,16 +464,12 @@ def __init__(self, version: Version, service_sid: str): - def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + def _create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> tuple: """ - Create the BuildInstance + Internal helper for create operation - :param asset_versions: The list of Asset Version resource SIDs to include in the Build. - :param function_versions: The list of the Function Version resource SIDs to include in the Build. - :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. - :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. - - :returns: The created BuildInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({ @@ -347,20 +488,43 @@ def create(self, asset_versions: Union[List[str], object]=values.unset, function headers["Accept"] = "application/json" - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers) + return self._version.create_with_response_info(method='POST', uri=self._uri, data=data, headers=headers) + def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + payload, _, _ = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) - async def create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + def create_with_http_info(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> ApiResponse: """ - Asynchronously create the BuildInstance + Create the BuildInstance and return response metadata :param asset_versions: The list of Asset Version resource SIDs to include in the Build. :param function_versions: The list of the Function Version resource SIDs to include in the Build. :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. - :returns: The created BuildInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({ @@ -379,9 +543,36 @@ async def create_async(self, asset_versions: Union[List[str], object]=values.uns headers["Accept"] = "application/json" - payload = await self._version.create_async(method='POST', uri=self._uri, data=data, headers=headers) + return await self._version.create_with_response_info_async(method='POST', uri=self._uri, data=data, headers=headers) + async def create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Asynchronously create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + payload, _, _ = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + async def create_with_http_info_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronously create the BuildInstance and return response metadata + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream(self, @@ -438,6 +629,58 @@ async def stream_async(self, return self._version.stream_async(page, limits['limit']) + def stream_with_http_info(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + page_size=limits['page_size'] + ) + + generator = self._version.stream(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits['page_size'] + ) + + generator = self._version.stream_async(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + def list(self, limit: Optional[int] = None, @@ -454,9 +697,10 @@ def list(self, the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - + :returns: list that will contain up to limit results """ + return list(self.stream( limit=limit, page_size=page_size, @@ -478,16 +722,68 @@ async def list_async(self, the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - + :returns: list that will contain up to limit results """ + return [record async for record in await self.stream_async( limit=limit, page_size=page_size, )] - def page(self, + + def list_with_http_info(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async(self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BuildInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page(self, + page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -517,10 +813,10 @@ def page(self, response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers) - return BuildPage(self._version, response, self._solution) + return BuildPage(self._version, response, solution=self._solution) async def page_async(self, - + page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -550,7 +846,75 @@ async def page_async(self, response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) - return BuildPage(self._version, response, self._solution) + return BuildPage(self._version, response, solution=self._solution) + + def page_with_http_info(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BuildPage, status code, and headers + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response, status_code, response_headers = self._version.page_with_response_info(method='GET', uri=self._uri, params=data, headers=headers) + page = BuildPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BuildPage, status code, and headers + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response, status_code, response_headers = await self._version.page_with_response_info_async(method='GET', uri=self._uri, params=data, headers=headers) + page = BuildPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BuildPage: """ @@ -565,7 +929,7 @@ def get_page(self, target_url: str) -> BuildPage: 'GET', target_url ) - return BuildPage(self._version, response, self._solution) + return BuildPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BuildPage: """ @@ -580,7 +944,7 @@ async def get_page_async(self, target_url: str) -> BuildPage: 'GET', target_url ) - return BuildPage(self._version, response, self._solution) + return BuildPage(self._version, response, solution=self._solution) @@ -610,3 +974,4 @@ def __repr__(self) -> str: """ return '<Twilio.Serverless.V1.BuildList>' + diff --git a/twilio/rest/serverless/v1/service/build/build_status.py b/twilio/rest/serverless/v1/service/build/build_status.py index e67c00e00e..03a81818c1 100644 --- a/twilio/rest/serverless/v1/service/build/build_status.py +++ b/twilio/rest/serverless/v1/service/build/build_status.py @@ -15,6 +15,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,9 +23,16 @@ + + + + + + class BuildStatusInstance(InstanceResource): + class Status(object): BUILDING = "building" COMPLETED = "completed" @@ -38,7 +46,7 @@ class Status(object): :ivar url: The absolute URL of the Build Status resource. """ - def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: str): + def __init__(self, version: Version, payload:Dict[str, Any], service_sid: str, sid: str): super().__init__(version) @@ -49,10 +57,13 @@ def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, self.url: Optional[str] = payload.get("url") + self._solution = { "service_sid": service_sid, "sid": sid, } + + self._context: Optional[BuildStatusContext] = None @property @@ -85,6 +96,24 @@ async def fetch_async(self) -> "BuildStatusInstance": :returns: The fetched BuildStatusInstance """ return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() def __repr__(self) -> str: """ @@ -97,6 +126,7 @@ def __repr__(self) -> str: class BuildStatusContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildStatusContext @@ -117,22 +147,31 @@ def __init__(self, version: Version, service_sid: str, sid: str): - def fetch(self) -> BuildStatusInstance: + def _fetch(self) -> tuple: """ - Fetch the BuildStatusInstance - + Internal helper for fetch operation - :returns: The fetched BuildStatusInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + headers["Accept"] = "application/json" - payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + return self._version.fetch_with_response_info(method='GET', uri=self._uri, headers=headers) + + def fetch(self) -> BuildStatusInstance: + """ + Fetch the BuildStatusInstance + + :returns: The fetched BuildStatusInstance + """ + payload, _, _ = self._fetch() return BuildStatusInstance( self._version, payload, @@ -141,22 +180,48 @@ def fetch(self) -> BuildStatusInstance: ) - async def fetch_async(self) -> BuildStatusInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BuildStatusInstance + Fetch the BuildStatusInstance and return response metadata - :returns: The fetched BuildStatusInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) + headers["Accept"] = "application/json" - payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) + async def fetch_async(self) -> BuildStatusInstance: + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + payload, _, _ = await self._fetch_async() return BuildStatusInstance( self._version, payload, @@ -164,6 +229,23 @@ async def fetch_async(self) -> BuildStatusInstance: sid=self._solution['sid'], ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BuildStatusInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: @@ -219,3 +301,4 @@ def __repr__(self) -> str: """ return '<Twilio.Serverless.V1.BuildStatusList>' + diff --git a/twilio/rest/serverless/v1/service/environment/__init__.py b/twilio/rest/serverless/v1/service/environment/__init__.py index cdad0504a7..f5817a338c 100644 --- a/twilio/rest/serverless/v1/service/environment/__init__.py +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[EnvironmentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EnvironmentInstance": """ Fetch the EnvironmentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "EnvironmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def deployments(self) -> DeploymentList: """ @@ -179,6 +217,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._logs: Optional[LogList] = None self._variables: Optional[VariableList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EnvironmentInstance @@ -186,10 +238,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EnvironmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -198,27 +272,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EnvironmentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> EnvironmentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the EnvironmentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched EnvironmentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> EnvironmentInstance: + """ + Fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + payload, _, _ = self._fetch() return EnvironmentInstance( self._version, payload, @@ -226,22 +316,46 @@ def fetch(self) -> EnvironmentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> EnvironmentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EnvironmentInstance + Fetch the EnvironmentInstance and return response metadata - :returns: The fetched EnvironmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EnvironmentInstance: + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + payload, _, _ = await self._fetch_async() return EnvironmentInstance( self._version, payload, @@ -249,6 +363,22 @@ async def fetch_async(self) -> EnvironmentInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EnvironmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def deployments(self) -> DeploymentList: """ @@ -306,6 +436,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: :param payload: Payload response from the API """ + return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -337,16 +468,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Environments".format(**self._solution) - def create( + def _create( self, unique_name: str, domain_suffix: Union[str, object] = values.unset - ) -> EnvironmentInstance: + ) -> tuple: """ - Create the EnvironmentInstance - - :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. - :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + Internal helper for create operation - :returns: The created EnvironmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -361,24 +490,55 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: str, domain_suffix: Union[str, object] = values.unset - ) -> EnvironmentInstance: + ) -> ApiResponse: """ - Asynchronously create the EnvironmentInstance + Create the EnvironmentInstance and return response metadata :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. - :returns: The created EnvironmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +553,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Asynchronously create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EnvironmentInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,6 +644,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EnvironmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EnvironmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -470,6 +713,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,6 +740,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -504,6 +749,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EnvironmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EnvironmentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -535,7 +830,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EnvironmentPage(self._version, response, self._solution) + return EnvironmentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -568,7 +863,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EnvironmentPage(self._version, response, self._solution) + return EnvironmentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EnvironmentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EnvironmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EnvironmentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EnvironmentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EnvironmentPage: """ @@ -580,7 +945,7 @@ def get_page(self, target_url: str) -> EnvironmentPage: :returns: Page of EnvironmentInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EnvironmentPage(self._version, response, self._solution) + return EnvironmentPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EnvironmentPage: """ @@ -592,7 +957,7 @@ async def get_page_async(self, target_url: str) -> EnvironmentPage: :returns: Page of EnvironmentInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EnvironmentPage(self._version, response, self._solution) + return EnvironmentPage(self._version, response, solution=self._solution) def get(self, sid: str) -> EnvironmentContext: """ diff --git a/twilio/rest/serverless/v1/service/environment/deployment.py b/twilio/rest/serverless/v1/service/environment/deployment.py index d28a4b8db1..65fecb891a 100644 --- a/twilio/rest/serverless/v1/service/environment/deployment.py +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[DeploymentContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "DeploymentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeploymentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeploymentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,20 +154,30 @@ def __init__( **self._solution ) - def fetch(self) -> DeploymentInstance: + def _fetch(self) -> tuple: """ - Fetch the DeploymentInstance - + Internal helper for fetch operation - :returns: The fetched DeploymentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DeploymentInstance: + """ + Fetch the DeploymentInstance + + :returns: The fetched DeploymentInstance + """ + payload, _, _ = self._fetch() return DeploymentInstance( self._version, payload, @@ -156,22 +186,47 @@ def fetch(self) -> DeploymentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> DeploymentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DeploymentInstance + Fetch the DeploymentInstance and return response metadata - :returns: The fetched DeploymentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DeploymentInstance: + """ + Asynchronous coroutine to fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + payload, _, _ = await self._fetch_async() return DeploymentInstance( self._version, payload, @@ -180,6 +235,23 @@ async def fetch_async(self) -> DeploymentInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeploymentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +270,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: :param payload: Payload response from the API """ + return DeploymentInstance( self._version, payload, @@ -238,18 +311,16 @@ def __init__(self, version: Version, service_sid: str, environment_sid: str): ) ) - def create( + def _create( self, build_sid: Union[str, object] = values.unset, is_plugin: Union[bool, object] = values.unset, - ) -> DeploymentInstance: + ) -> tuple: """ - Create the DeploymentInstance - - :param build_sid: The SID of the Build for the Deployment. - :param is_plugin: Whether the Deployment is a plugin. + Internal helper for create operation - :returns: The created DeploymentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -264,10 +335,24 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + payload, _, _ = self._create(build_sid=build_sid, is_plugin=is_plugin) return DeploymentInstance( self._version, payload, @@ -275,18 +360,40 @@ def create( environment_sid=self._solution["environment_sid"], ) - async def create_async( + def create_with_http_info( self, build_sid: Union[str, object] = values.unset, is_plugin: Union[bool, object] = values.unset, - ) -> DeploymentInstance: + ) -> ApiResponse: """ - Asynchronously create the DeploymentInstance + Create the DeploymentInstance and return response metadata :param build_sid: The SID of the Build for the Deployment. :param is_plugin: Whether the Deployment is a plugin. - :returns: The created DeploymentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + build_sid=build_sid, is_plugin=is_plugin + ) + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -301,10 +408,26 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Asynchronously create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + payload, _, _ = await self._create_async( + build_sid=build_sid, is_plugin=is_plugin + ) return DeploymentInstance( self._version, payload, @@ -312,6 +435,30 @@ async def create_async( environment_sid=self._solution["environment_sid"], ) + async def create_with_http_info_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the DeploymentInstance and return response metadata + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + build_sid=build_sid, is_plugin=is_plugin + ) + instance = DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -362,6 +509,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -381,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -407,6 +605,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -415,6 +614,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DeploymentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -446,7 +695,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DeploymentPage(self._version, response, self._solution) + return DeploymentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -479,7 +728,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DeploymentPage(self._version, response, self._solution) + return DeploymentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeploymentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DeploymentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DeploymentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DeploymentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DeploymentPage: """ @@ -491,7 +810,7 @@ def get_page(self, target_url: str) -> DeploymentPage: :returns: Page of DeploymentInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DeploymentPage(self._version, response, self._solution) + return DeploymentPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DeploymentPage: """ @@ -503,7 +822,7 @@ async def get_page_async(self, target_url: str) -> DeploymentPage: :returns: Page of DeploymentInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DeploymentPage(self._version, response, self._solution) + return DeploymentPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DeploymentContext: """ diff --git a/twilio/rest/serverless/v1/service/environment/log.py b/twilio/rest/serverless/v1/service/environment/log.py index a3c9a6c2da..30ff705ac5 100644 --- a/twilio/rest/serverless/v1/service/environment/log.py +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,12 +24,6 @@ class LogInstance(InstanceResource): - - class Level(object): - INFO = "info" - WARN = "warn" - ERROR = "error" - """ :ivar sid: The unique string that we created to identify the Log resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Log resource. @@ -38,7 +33,7 @@ class Level(object): :ivar deployment_sid: The SID of the deployment that corresponds to the log. :ivar function_sid: The SID of the function whose invocation produced the log. :ivar request_sid: The SID of the request associated with the log. - :ivar level: + :ivar level: The log level. :ivar message: The log message. :ivar date_created: The date and time in GMT when the Log resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the Log resource. @@ -62,7 +57,7 @@ def __init__( self.deployment_sid: Optional[str] = payload.get("deployment_sid") self.function_sid: Optional[str] = payload.get("function_sid") self.request_sid: Optional[str] = payload.get("request_sid") - self.level: Optional["LogInstance.Level"] = payload.get("level") + self.level: Optional[str] = payload.get("level") self.message: Optional[str] = payload.get("message") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -74,6 +69,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[LogContext] = None @property @@ -111,6 +107,24 @@ async def fetch_async(self) -> "LogInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LogInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LogInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,20 +162,30 @@ def __init__( ) ) - def fetch(self) -> LogInstance: + def _fetch(self) -> tuple: """ - Fetch the LogInstance + Internal helper for fetch operation - - :returns: The fetched LogInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> LogInstance: + """ + Fetch the LogInstance + + :returns: The fetched LogInstance + """ + payload, _, _ = self._fetch() return LogInstance( self._version, payload, @@ -170,22 +194,47 @@ def fetch(self) -> LogInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> LogInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the LogInstance + Fetch the LogInstance and return response metadata - :returns: The fetched LogInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> LogInstance: + """ + Asynchronous coroutine to fetch the LogInstance + + + :returns: The fetched LogInstance + """ + payload, _, _ = await self._fetch_async() return LogInstance( self._version, payload, @@ -194,6 +243,23 @@ async def fetch_async(self) -> LogInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LogInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -212,6 +278,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LogInstance: :param payload: Payload response from the API """ + return LogInstance( self._version, payload, @@ -324,6 +391,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LogInstance and returns headers from first page + + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LogInstance and returns headers from first page + + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, function_sid: Union[str, object] = values.unset, @@ -349,6 +486,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( function_sid=function_sid, @@ -384,6 +522,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -395,6 +534,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LogInstance and returns headers from first page + + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LogInstance and returns headers from first page + + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, function_sid: Union[str, object] = values.unset, @@ -435,7 +642,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return LogPage(self._version, response, self._solution) + return LogPage(self._version, response, solution=self._solution) async def page_async( self, @@ -477,7 +684,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return LogPage(self._version, response, self._solution) + return LogPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LogPage, status code, and headers + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = LogPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with LogPage, status code, and headers + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = LogPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> LogPage: """ @@ -489,7 +784,7 @@ def get_page(self, target_url: str) -> LogPage: :returns: Page of LogInstance """ response = self._version.domain.twilio.request("GET", target_url) - return LogPage(self._version, response, self._solution) + return LogPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> LogPage: """ @@ -501,7 +796,7 @@ async def get_page_async(self, target_url: str) -> LogPage: :returns: Page of LogInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return LogPage(self._version, response, self._solution) + return LogPage(self._version, response, solution=self._solution) def get(self, sid: str) -> LogContext: """ diff --git a/twilio/rest/serverless/v1/service/environment/variable.py b/twilio/rest/serverless/v1/service/environment/variable.py index fbc6b48ac8..13597a5419 100644 --- a/twilio/rest/serverless/v1/service/environment/variable.py +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[VariableContext] = None @property @@ -101,6 +103,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "VariableInstance": """ Fetch the VariableInstance @@ -119,6 +139,24 @@ async def fetch_async(self) -> "VariableInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, key: Union[str, object] = values.unset, @@ -155,6 +193,42 @@ async def update_async( value=value, ) + def update_with_http_info( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the VariableInstance with HTTP info + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + key=key, + value=value, + ) + + async def update_with_http_info_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VariableInstance with HTTP info + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + key=key, + value=value, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -190,6 +264,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the VariableInstance @@ -197,10 +285,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the VariableInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -209,27 +319,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the VariableInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> VariableInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the VariableInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched VariableInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VariableInstance: + """ + Fetch the VariableInstance + + :returns: The fetched VariableInstance + """ + payload, _, _ = self._fetch() return VariableInstance( self._version, payload, @@ -238,22 +364,47 @@ def fetch(self) -> VariableInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> VariableInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the VariableInstance + Fetch the VariableInstance and return response metadata - :returns: The fetched VariableInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> VariableInstance: + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + payload, _, _ = await self._fetch_async() return VariableInstance( self._version, payload, @@ -262,18 +413,33 @@ async def fetch_async(self) -> VariableInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VariableInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, key: Union[str, object] = values.unset, value: Union[str, object] = values.unset, - ) -> VariableInstance: + ) -> tuple: """ - Update the VariableInstance + Internal helper for update operation - :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. - :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. - - :returns: The updated VariableInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -288,10 +454,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + payload, _, _ = self._update(key=key, value=value) return VariableInstance( self._version, payload, @@ -300,18 +480,39 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, key: Union[str, object] = values.unset, value: Union[str, object] = values.unset, - ) -> VariableInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the VariableInstance + Update the VariableInstance and return response metadata :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. - :returns: The updated VariableInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,10 +527,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + payload, _, _ = await self._update_async(key=key, value=value) return VariableInstance( self._version, payload, @@ -338,6 +553,29 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VariableInstance and return response metadata + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -356,6 +594,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: :param payload: Payload response from the API """ + return VariableInstance( self._version, payload, @@ -396,14 +635,12 @@ def __init__(self, version: Version, service_sid: str, environment_sid: str): ) ) - def create(self, key: str, value: str) -> VariableInstance: + def _create(self, key: str, value: str) -> tuple: """ - Create the VariableInstance + Internal helper for create operation - :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. - :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. - - :returns: The created VariableInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,10 +655,20 @@ def create(self, key: str, value: str) -> VariableInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, key: str, value: str) -> VariableInstance: + """ + Create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + payload, _, _ = self._create(key=key, value=value) return VariableInstance( self._version, payload, @@ -429,14 +676,30 @@ def create(self, key: str, value: str) -> VariableInstance: environment_sid=self._solution["environment_sid"], ) - async def create_async(self, key: str, value: str) -> VariableInstance: + def create_with_http_info(self, key: str, value: str) -> ApiResponse: """ - Asynchronously create the VariableInstance + Create the VariableInstance and return response metadata :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. - :returns: The created VariableInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, key: str, value: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -451,10 +714,20 @@ async def create_async(self, key: str, value: str) -> VariableInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, key: str, value: str) -> VariableInstance: + """ + Asynchronously create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + payload, _, _ = await self._create_async(key=key, value=value) return VariableInstance( self._version, payload, @@ -462,6 +735,24 @@ async def create_async(self, key: str, value: str) -> VariableInstance: environment_sid=self._solution["environment_sid"], ) + async def create_with_http_info_async(self, key: str, value: str) -> ApiResponse: + """ + Asynchronously create the VariableInstance and return response metadata + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -512,6 +803,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VariableInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VariableInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -531,6 +872,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -557,6 +899,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -565,6 +908,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VariableInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VariableInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -596,7 +989,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return VariablePage(self._version, response, self._solution) + return VariablePage(self._version, response, solution=self._solution) async def page_async( self, @@ -629,7 +1022,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return VariablePage(self._version, response, self._solution) + return VariablePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VariablePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VariablePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VariablePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VariablePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> VariablePage: """ @@ -641,7 +1104,7 @@ def get_page(self, target_url: str) -> VariablePage: :returns: Page of VariableInstance """ response = self._version.domain.twilio.request("GET", target_url) - return VariablePage(self._version, response, self._solution) + return VariablePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> VariablePage: """ @@ -653,7 +1116,7 @@ async def get_page_async(self, target_url: str) -> VariablePage: :returns: Page of VariableInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return VariablePage(self._version, response, self._solution) + return VariablePage(self._version, response, solution=self._solution) def get(self, sid: str) -> VariableContext: """ diff --git a/twilio/rest/serverless/v1/service/function/__init__.py b/twilio/rest/serverless/v1/service/function/__init__.py index 7697587e60..31c142d1f8 100644 --- a/twilio/rest/serverless/v1/service/function/__init__.py +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[FunctionContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FunctionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FunctionInstance": """ Fetch the FunctionInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "FunctionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "FunctionInstance": """ Update the FunctionInstance @@ -141,6 +179,30 @@ async def update_async(self, friendly_name: str) -> "FunctionInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the FunctionInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the FunctionInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def function_versions(self) -> FunctionVersionList: """ @@ -179,6 +241,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._function_versions: Optional[FunctionVersionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FunctionInstance @@ -186,10 +262,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FunctionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -198,27 +296,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> FunctionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the FunctionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched FunctionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FunctionInstance: + """ + Fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + payload, _, _ = self._fetch() return FunctionInstance( self._version, payload, @@ -226,22 +340,46 @@ def fetch(self) -> FunctionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> FunctionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FunctionInstance + Fetch the FunctionInstance and return response metadata - :returns: The fetched FunctionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FunctionInstance: + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + payload, _, _ = await self._fetch_async() return FunctionInstance( self._version, payload, @@ -249,13 +387,28 @@ async def fetch_async(self) -> FunctionInstance: sid=self._solution["sid"], ) - def update(self, friendly_name: str) -> FunctionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the FunctionInstance + Asynchronous coroutine to fetch the FunctionInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. - :returns: The updated FunctionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -269,10 +422,19 @@ def update(self, friendly_name: str) -> FunctionInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, friendly_name: str) -> FunctionInstance: + """ + Update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return FunctionInstance( self._version, payload, @@ -280,13 +442,29 @@ def update(self, friendly_name: str) -> FunctionInstance: sid=self._solution["sid"], ) - async def update_async(self, friendly_name: str) -> FunctionInstance: + def update_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronous coroutine to update the FunctionInstance + Update the FunctionInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. - :returns: The updated FunctionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -300,10 +478,19 @@ async def update_async(self, friendly_name: str) -> FunctionInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return FunctionInstance( self._version, payload, @@ -311,6 +498,25 @@ async def update_async(self, friendly_name: str) -> FunctionInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the FunctionInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def function_versions(self) -> FunctionVersionList: """ @@ -342,6 +548,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: :param payload: Payload response from the API """ + return FunctionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -373,13 +580,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Functions".format(**self._solution) - def create(self, friendly_name: str) -> FunctionInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the FunctionInstance - - :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + Internal helper for create operation - :returns: The created FunctionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,21 +599,43 @@ def create(self, friendly_name: str) -> FunctionInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, friendly_name: str) -> FunctionInstance: + """ + Create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return FunctionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, friendly_name: str) -> FunctionInstance: + def create_with_http_info(self, friendly_name: str) -> ApiResponse: """ - Asynchronously create the FunctionInstance + Create the FunctionInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. - :returns: The created FunctionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, friendly_name: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -421,14 +649,39 @@ async def create_async(self, friendly_name: str) -> FunctionInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronously create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return FunctionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronously create the FunctionInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -479,6 +732,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FunctionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FunctionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -498,6 +801,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -524,6 +828,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -532,6 +837,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FunctionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FunctionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -563,7 +918,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return FunctionPage(self._version, response, self._solution) + return FunctionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -596,7 +951,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return FunctionPage(self._version, response, self._solution) + return FunctionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FunctionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FunctionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> FunctionPage: """ @@ -608,7 +1033,7 @@ def get_page(self, target_url: str) -> FunctionPage: :returns: Page of FunctionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return FunctionPage(self._version, response, self._solution) + return FunctionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> FunctionPage: """ @@ -620,7 +1045,7 @@ async def get_page_async(self, target_url: str) -> FunctionPage: :returns: Page of FunctionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return FunctionPage(self._version, response, self._solution) + return FunctionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> FunctionContext: """ diff --git a/twilio/rest/serverless/v1/service/function/function_version/__init__.py b/twilio/rest/serverless/v1/service/function/function_version/__init__.py index 88b666208c..75cdb11b4f 100644 --- a/twilio/rest/serverless/v1/service/function/function_version/__init__.py +++ b/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "function_sid": function_sid, "sid": sid or self.sid, } + self._context: Optional[FunctionVersionContext] = None @property @@ -110,6 +112,24 @@ async def fetch_async(self) -> "FunctionVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def function_version_content(self) -> FunctionVersionContentList: """ @@ -154,20 +174,30 @@ def __init__(self, version: Version, service_sid: str, function_sid: str, sid: s self._function_version_content: Optional[FunctionVersionContentList] = None - def fetch(self) -> FunctionVersionInstance: + def _fetch(self) -> tuple: """ - Fetch the FunctionVersionInstance - + Internal helper for fetch operation - :returns: The fetched FunctionVersionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FunctionVersionInstance: + """ + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + payload, _, _ = self._fetch() return FunctionVersionInstance( self._version, payload, @@ -176,22 +206,47 @@ def fetch(self) -> FunctionVersionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> FunctionVersionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FunctionVersionInstance + Fetch the FunctionVersionInstance and return response metadata - :returns: The fetched FunctionVersionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FunctionVersionInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + payload, _, _ = await self._fetch_async() return FunctionVersionInstance( self._version, payload, @@ -200,6 +255,23 @@ async def fetch_async(self) -> FunctionVersionInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def function_version_content(self) -> FunctionVersionContentList: """ @@ -232,6 +304,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: :param payload: Payload response from the API """ + return FunctionVersionInstance( self._version, payload, @@ -320,6 +393,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -339,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -365,6 +489,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -373,6 +498,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FunctionVersionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -404,7 +579,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return FunctionVersionPage(self._version, response, self._solution) + return FunctionVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -437,7 +612,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return FunctionVersionPage(self._version, response, self._solution) + return FunctionVersionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FunctionVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FunctionVersionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FunctionVersionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> FunctionVersionPage: """ @@ -449,7 +694,7 @@ def get_page(self, target_url: str) -> FunctionVersionPage: :returns: Page of FunctionVersionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return FunctionVersionPage(self._version, response, self._solution) + return FunctionVersionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> FunctionVersionPage: """ @@ -461,7 +706,7 @@ async def get_page_async(self, target_url: str) -> FunctionVersionPage: :returns: Page of FunctionVersionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return FunctionVersionPage(self._version, response, self._solution) + return FunctionVersionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> FunctionVersionContext: """ diff --git a/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py b/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py index f16833da2a..a253ad6ca9 100644 --- a/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py +++ b/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "function_sid": function_sid, "sid": sid, } + self._context: Optional[FunctionVersionContentContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "FunctionVersionContentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -124,20 +144,30 @@ def __init__(self, version: Version, service_sid: str, function_sid: str, sid: s **self._solution ) - def fetch(self) -> FunctionVersionContentInstance: + def _fetch(self) -> tuple: """ - Fetch the FunctionVersionContentInstance - + Internal helper for fetch operation - :returns: The fetched FunctionVersionContentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionVersionContentInstance: + """ + Fetch the FunctionVersionContentInstance + + :returns: The fetched FunctionVersionContentInstance + """ + payload, _, _ = self._fetch() return FunctionVersionContentInstance( self._version, payload, @@ -146,22 +176,47 @@ def fetch(self) -> FunctionVersionContentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> FunctionVersionContentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FunctionVersionContentInstance + Fetch the FunctionVersionContentInstance and return response metadata - :returns: The fetched FunctionVersionContentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FunctionVersionContentInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + payload, _, _ = await self._fetch_async() return FunctionVersionContentInstance( self._version, payload, @@ -170,6 +225,23 @@ async def fetch_async(self) -> FunctionVersionContentInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v1/flow/__init__.py b/twilio/rest/studio/v1/flow/__init__.py index 533c1a45f5..a2795280f7 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlowContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlowInstance": """ Fetch the FlowInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "FlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def engagements(self) -> EngagementList: """ @@ -161,6 +199,20 @@ def __init__(self, version: Version, sid: str): self._engagements: Optional[EngagementList] = None self._executions: Optional[ExecutionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlowInstance @@ -168,10 +220,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -180,55 +254,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> FlowInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the FlowInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched FlowInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + payload, _, _ = self._fetch() return FlowInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> FlowInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlowInstance + Fetch the FlowInstance and return response metadata - :returns: The fetched FlowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + payload, _, _ = await self._fetch_async() return FlowInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def engagements(self) -> EngagementList: """ @@ -271,6 +399,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -345,6 +474,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -364,6 +543,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -390,6 +570,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -398,6 +579,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -464,6 +695,76 @@ async def page_async( ) return FlowPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> FlowPage: """ Retrieve a specific page of FlowInstance records from the API. diff --git a/twilio/rest/studio/v1/flow/engagement/__init__.py b/twilio/rest/studio/v1/flow/engagement/__init__.py index 759d92506c..a899206caf 100644 --- a/twilio/rest/studio/v1/flow/engagement/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[EngagementContext] = None @property @@ -113,6 +115,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EngagementInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EngagementInstance": """ Fetch the EngagementInstance @@ -131,6 +151,24 @@ async def fetch_async(self) -> "EngagementInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EngagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def engagement_context(self) -> EngagementContextList: """ @@ -177,6 +215,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._engagement_context: Optional[EngagementContextList] = None self._steps: Optional[StepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EngagementInstance @@ -184,10 +236,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EngagementInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -196,27 +270,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> EngagementInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the EngagementInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched EngagementInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> EngagementInstance: + """ + Fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + payload, _, _ = self._fetch() return EngagementInstance( self._version, payload, @@ -224,22 +314,46 @@ def fetch(self) -> EngagementInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> EngagementInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EngagementInstance + Fetch the EngagementInstance and return response metadata - :returns: The fetched EngagementInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EngagementInstance: + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + payload, _, _ = await self._fetch_async() return EngagementInstance( self._version, payload, @@ -247,6 +361,22 @@ async def fetch_async(self) -> EngagementInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def engagement_context(self) -> EngagementContextList: """ @@ -291,6 +421,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: :param payload: Payload response from the API """ + return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -322,17 +453,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> EngagementInstance: + ) -> tuple: """ - Create the EngagementInstance + Internal helper for create operation - :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` - :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. - - :returns: The created EngagementInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -348,25 +476,55 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> EngagementInstance: + ) -> ApiResponse: """ - Asynchronously create the EngagementInstance + Create the EngagementInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. - :returns: The created EngagementInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -382,14 +540,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Asynchronously create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EngagementInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -440,6 +633,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EngagementInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EngagementInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -459,6 +702,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -485,6 +729,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -493,6 +738,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EngagementInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EngagementInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -524,7 +819,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EngagementPage(self._version, response, self._solution) + return EngagementPage(self._version, response, solution=self._solution) async def page_async( self, @@ -557,7 +852,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EngagementPage(self._version, response, self._solution) + return EngagementPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EngagementPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EngagementPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EngagementPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EngagementPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EngagementPage: """ @@ -569,7 +934,7 @@ def get_page(self, target_url: str) -> EngagementPage: :returns: Page of EngagementInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EngagementPage(self._version, response, self._solution) + return EngagementPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EngagementPage: """ @@ -581,7 +946,7 @@ async def get_page_async(self, target_url: str) -> EngagementPage: :returns: Page of EngagementInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EngagementPage(self._version, response, self._solution) + return EngagementPage(self._version, response, solution=self._solution) def get(self, sid: str) -> EngagementContext: """ diff --git a/twilio/rest/studio/v1/flow/engagement/engagement_context.py b/twilio/rest/studio/v1/flow/engagement/engagement_context.py index 73161011eb..3b0cf3cf52 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "engagement_sid": engagement_sid, } + self._context: Optional[EngagementContextContext] = None @property @@ -84,6 +86,24 @@ async def fetch_async(self) -> "EngagementContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EngagementContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,20 +135,30 @@ def __init__(self, version: Version, flow_sid: str, engagement_sid: str): **self._solution ) - def fetch(self) -> EngagementContextInstance: + def _fetch(self) -> tuple: """ - Fetch the EngagementContextInstance - + Internal helper for fetch operation - :returns: The fetched EngagementContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EngagementContextInstance: + """ + Fetch the EngagementContextInstance + + :returns: The fetched EngagementContextInstance + """ + payload, _, _ = self._fetch() return EngagementContextInstance( self._version, payload, @@ -136,22 +166,46 @@ def fetch(self) -> EngagementContextInstance: engagement_sid=self._solution["engagement_sid"], ) - async def fetch_async(self) -> EngagementContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EngagementContextInstance + Fetch the EngagementContextInstance and return response metadata - :returns: The fetched EngagementContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EngagementContextInstance: + """ + Asynchronous coroutine to fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + payload, _, _ = await self._fetch_async() return EngagementContextInstance( self._version, payload, @@ -159,6 +213,22 @@ async def fetch_async(self) -> EngagementContextInstance: engagement_sid=self._solution["engagement_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/twilio/rest/studio/v1/flow/engagement/step/__init__.py index d88d0ad0f6..25a925f124 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,8 +32,10 @@ class StepInstance(InstanceResource): :ivar engagement_sid: The SID of the Engagement. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar parent_step_sid: The SID of the parent Step. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,8 +58,10 @@ def __init__( self.engagement_sid: Optional[str] = payload.get("engagement_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -71,6 +76,7 @@ def __init__( "engagement_sid": engagement_sid, "sid": sid or self.sid, } + self._context: Optional[StepContext] = None @property @@ -108,6 +114,24 @@ async def fetch_async(self) -> "StepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> StepContextList: """ @@ -150,20 +174,30 @@ def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: st self._step_context: Optional[StepContextList] = None - def fetch(self) -> StepInstance: + def _fetch(self) -> tuple: """ - Fetch the StepInstance - + Internal helper for fetch operation - :returns: The fetched StepInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> StepInstance: + """ + Fetch the StepInstance + + + :returns: The fetched StepInstance + """ + payload, _, _ = self._fetch() return StepInstance( self._version, payload, @@ -172,22 +206,47 @@ def fetch(self) -> StepInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> StepInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the StepInstance + Fetch the StepInstance and return response metadata - :returns: The fetched StepInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> StepInstance: + """ + Asynchronous coroutine to fetch the StepInstance + + + :returns: The fetched StepInstance + """ + payload, _, _ = await self._fetch_async() return StepInstance( self._version, payload, @@ -196,6 +255,23 @@ async def fetch_async(self) -> StepInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def step_context(self) -> StepContextList: """ @@ -228,6 +304,7 @@ def get_instance(self, payload: Dict[str, Any]) -> StepInstance: :param payload: Payload response from the API """ + return StepInstance( self._version, payload, @@ -316,6 +393,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -335,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -361,6 +489,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -369,6 +498,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists StepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -400,7 +579,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return StepPage(self._version, response, self._solution) + return StepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -433,7 +612,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return StepPage(self._version, response, self._solution) + return StepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = StepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with StepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = StepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> StepPage: """ @@ -445,7 +694,7 @@ def get_page(self, target_url: str) -> StepPage: :returns: Page of StepInstance """ response = self._version.domain.twilio.request("GET", target_url) - return StepPage(self._version, response, self._solution) + return StepPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> StepPage: """ @@ -457,7 +706,7 @@ async def get_page_async(self, target_url: str) -> StepPage: :returns: Page of StepInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return StepPage(self._version, response, self._solution) + return StepPage(self._version, response, solution=self._solution) def get(self, sid: str) -> StepContext: """ diff --git a/twilio/rest/studio/v1/flow/engagement/step/step_context.py b/twilio/rest/studio/v1/flow/engagement/step/step_context.py index 6b299ebe5d..26f82d470d 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/step_context.py +++ b/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "engagement_sid": engagement_sid, "step_sid": step_sid, } + self._context: Optional[StepContextContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "StepContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -124,20 +144,30 @@ def __init__( **self._solution ) - def fetch(self) -> StepContextInstance: + def _fetch(self) -> tuple: """ - Fetch the StepContextInstance - + Internal helper for fetch operation - :returns: The fetched StepContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> StepContextInstance: + """ + Fetch the StepContextInstance + + :returns: The fetched StepContextInstance + """ + payload, _, _ = self._fetch() return StepContextInstance( self._version, payload, @@ -146,22 +176,47 @@ def fetch(self) -> StepContextInstance: step_sid=self._solution["step_sid"], ) - async def fetch_async(self) -> StepContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the StepContextInstance + Fetch the StepContextInstance and return response metadata - :returns: The fetched StepContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> StepContextInstance: + """ + Asynchronous coroutine to fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + payload, _, _ = await self._fetch_async() return StepContextInstance( self._version, payload, @@ -170,6 +225,23 @@ async def fetch_async(self) -> StepContextInstance: step_sid=self._solution["step_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v1/flow/execution/__init__.py b/twilio/rest/studio/v1/flow/execution/__init__.py index 624b381768..5ee77d109e 100644 --- a/twilio/rest/studio/v1/flow/execution/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ExecutionInstance": """ Fetch the ExecutionInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "ExecutionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ Update the ExecutionInstance @@ -155,6 +193,32 @@ async def update_async( status=status, ) + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def execution_context(self) -> ExecutionContextList: """ @@ -201,6 +265,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._execution_context: Optional[ExecutionContextList] = None self._steps: Optional[ExecutionStepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ExecutionInstance @@ -208,10 +286,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -220,27 +320,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ExecutionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ExecutionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = self._fetch() return ExecutionInstance( self._version, payload, @@ -248,22 +364,46 @@ def fetch(self) -> ExecutionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ExecutionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionInstance + Fetch the ExecutionInstance and return response metadata - :returns: The fetched ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionInstance( self._version, payload, @@ -271,13 +411,28 @@ async def fetch_async(self) -> ExecutionInstance: sid=self._solution["sid"], ) - def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ExecutionInstance + Asynchronous coroutine to fetch the ExecutionInstance and return response metadata - :param status: - :returns: The updated ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -291,10 +446,19 @@ def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = self._update(status=status) return ExecutionInstance( self._version, payload, @@ -302,15 +466,29 @@ def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: sid=self._solution["sid"], ) - async def update_async( - self, status: "ExecutionInstance.Status" - ) -> ExecutionInstance: + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: """ - Asynchronous coroutine to update the ExecutionInstance + Update the ExecutionInstance and return response metadata :param status: - :returns: The updated ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -324,10 +502,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = await self._update_async(status=status) return ExecutionInstance( self._version, payload, @@ -335,6 +524,25 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def execution_context(self) -> ExecutionContextList: """ @@ -379,6 +587,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -410,17 +619,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> tuple: """ - Create the ExecutionInstance + Internal helper for create operation - :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. - :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. - - :returns: The created ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -436,25 +642,55 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> ApiResponse: """ - Asynchronously create the ExecutionInstance + Create the ExecutionInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. - :returns: The created ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -470,14 +706,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ExecutionInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, date_created_from: Union[datetime, object] = values.unset, @@ -544,6 +815,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ExecutionInstance and returns headers from first page + + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ExecutionInstance and returns headers from first page + + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created_from: Union[datetime, object] = values.unset, @@ -567,6 +902,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_from=date_created_from, @@ -599,6 +935,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -609,6 +946,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ExecutionInstance and returns headers from first page + + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ExecutionInstance and returns headers from first page + + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created_from: Union[datetime, object] = values.unset, @@ -646,7 +1045,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -685,7 +1084,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ExecutionPage: """ @@ -697,7 +1178,7 @@ def get_page(self, target_url: str) -> ExecutionPage: :returns: Page of ExecutionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ExecutionPage: """ @@ -709,7 +1190,7 @@ async def get_page_async(self, target_url: str) -> ExecutionPage: :returns: Page of ExecutionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ExecutionContext: """ diff --git a/twilio/rest/studio/v1/flow/execution/execution_context.py b/twilio/rest/studio/v1/flow/execution/execution_context.py index 0841a9ef24..d12c6b3f93 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -84,6 +86,24 @@ async def fetch_async(self) -> "ExecutionContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,20 +135,30 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str): **self._solution ) - def fetch(self) -> ExecutionContextInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionContextInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + :returns: The fetched ExecutionContextInstance + """ + payload, _, _ = self._fetch() return ExecutionContextInstance( self._version, payload, @@ -136,22 +166,46 @@ def fetch(self) -> ExecutionContextInstance: execution_sid=self._solution["execution_sid"], ) - async def fetch_async(self) -> ExecutionContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionContextInstance + Fetch the ExecutionContextInstance and return response metadata - :returns: The fetched ExecutionContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionContextInstance( self._version, payload, @@ -159,6 +213,22 @@ async def fetch_async(self) -> ExecutionContextInstance: execution_sid=self._solution["execution_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py index 888506e965..d09adb9984 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,10 +32,12 @@ class ExecutionStepInstance(InstanceResource): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. :ivar flow_sid: The SID of the Flow. :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: This field shows the Step SID of the Widget in the parent Flow that started the Subflow. If this Step is not part of a Subflow execution, the value is null. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,10 +58,12 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.flow_sid: Optional[str] = payload.get("flow_sid") self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -73,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -110,6 +116,24 @@ async def fetch_async(self) -> "ExecutionStepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> ExecutionStepContextList: """ @@ -152,20 +176,30 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str self._step_context: Optional[ExecutionStepContextList] = None - def fetch(self) -> ExecutionStepInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionStepInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionStepInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + payload, _, _ = self._fetch() return ExecutionStepInstance( self._version, payload, @@ -174,22 +208,47 @@ def fetch(self) -> ExecutionStepInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ExecutionStepInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionStepInstance + Fetch the ExecutionStepInstance and return response metadata - :returns: The fetched ExecutionStepInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionStepInstance( self._version, payload, @@ -198,6 +257,23 @@ async def fetch_async(self) -> ExecutionStepInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def step_context(self) -> ExecutionStepContextList: """ @@ -230,6 +306,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -318,6 +395,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -337,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -363,6 +491,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -371,6 +500,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -402,7 +581,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -435,7 +614,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionStepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionStepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ExecutionStepPage: """ @@ -447,7 +696,7 @@ def get_page(self, target_url: str) -> ExecutionStepPage: :returns: Page of ExecutionStepInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ @@ -459,7 +708,7 @@ async def get_page_async(self, target_url: str) -> ExecutionStepPage: :returns: Page of ExecutionStepInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ExecutionStepContext: """ diff --git a/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py index 78249a9562..469a2e48c4 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "ExecutionStepContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -124,20 +144,30 @@ def __init__( **self._solution ) - def fetch(self) -> ExecutionStepContextInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionStepContextInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionStepContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + :returns: The fetched ExecutionStepContextInstance + """ + payload, _, _ = self._fetch() return ExecutionStepContextInstance( self._version, payload, @@ -146,22 +176,47 @@ def fetch(self) -> ExecutionStepContextInstance: step_sid=self._solution["step_sid"], ) - async def fetch_async(self) -> ExecutionStepContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionStepContextInstance + Fetch the ExecutionStepContextInstance and return response metadata - :returns: The fetched ExecutionStepContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionStepContextInstance( self._version, payload, @@ -170,6 +225,23 @@ async def fetch_async(self) -> ExecutionStepContextInstance: step_sid=self._solution["step_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v2/flow/__init__.py b/twilio/rest/studio/v2/flow/__init__.py index b4c542fdc0..c13e10be4c 100644 --- a/twilio/rest/studio/v2/flow/__init__.py +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -34,6 +35,7 @@ class Status(object): """ :ivar sid: The unique string that we created to identify the Flow resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar author_sid: The SID of the User that created or last updated the Flow. :ivar friendly_name: The string that you assigned to describe the Flow. :ivar definition: JSON representation of flow definition. :ivar status: @@ -56,6 +58,7 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.account_sid: Optional[str] = payload.get("account_sid") + self.author_sid: Optional[str] = payload.get("author_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.definition: Optional[Dict[str, object]] = payload.get("definition") self.status: Optional["FlowInstance.Status"] = payload.get("status") @@ -77,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlowContext] = None @property @@ -112,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlowInstance": """ Fetch the FlowInstance @@ -130,12 +152,31 @@ async def fetch_async(self) -> "FlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "FlowInstance.Status", friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> "FlowInstance": """ Update the FlowInstance @@ -144,6 +185,7 @@ def update( :param friendly_name: The string that you assigned to describe the Flow. :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. :returns: The updated FlowInstance """ @@ -152,6 +194,7 @@ def update( friendly_name=friendly_name, definition=definition, commit_message=commit_message, + author_sid=author_sid, ) async def update_async( @@ -160,6 +203,7 @@ async def update_async( friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> "FlowInstance": """ Asynchronous coroutine to update the FlowInstance @@ -168,6 +212,7 @@ async def update_async( :param friendly_name: The string that you assigned to describe the Flow. :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. :returns: The updated FlowInstance """ @@ -176,6 +221,61 @@ async def update_async( friendly_name=friendly_name, definition=definition, commit_message=commit_message, + author_sid=author_sid, + ) + + def update_with_http_info( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowInstance with HTTP info + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + + async def update_with_http_info_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowInstance with HTTP info + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, ) @property @@ -230,6 +330,20 @@ def __init__(self, version: Version, sid: str): self._revisions: Optional[FlowRevisionList] = None self._test_users: Optional[FlowTestUserList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlowInstance @@ -237,10 +351,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -249,71 +385,122 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> FlowInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the FlowInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched FlowInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + :returns: The fetched FlowInstance + """ + payload, _, _ = self._fetch() return FlowInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> FlowInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlowInstance + Fetch the FlowInstance and return response metadata - :returns: The fetched FlowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + payload, _, _ = await self._fetch_async() return FlowInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: "FlowInstance.Status", friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, - ) -> FlowInstance: + author_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Update the FlowInstance + Internal helper for update operation - :param status: - :param friendly_name: The string that you assigned to describe the Flow. - :param definition: JSON representation of flow definition. - :param commit_message: Description of change made in the revision. - - :returns: The updated FlowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -322,6 +509,7 @@ def update( "FriendlyName": friendly_name, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) headers = values.of({}) @@ -330,29 +518,81 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return FlowInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, status: "FlowInstance.Status", friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> FlowInstance: """ - Asynchronous coroutine to update the FlowInstance + Update the FlowInstance :param status: :param friendly_name: The string that you assigned to describe the Flow. :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. :returns: The updated FlowInstance """ + payload, _, _ = self._update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowInstance and return response metadata + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -360,6 +600,7 @@ async def update_async( "FriendlyName": friendly_name, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) headers = values.of({}) @@ -368,12 +609,67 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: The updated FlowInstance + """ + payload, _, _ = await self._update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) return FlowInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowInstance and return response metadata + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def executions(self) -> ExecutionList: """ @@ -428,6 +724,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -452,22 +749,19 @@ def __init__(self, version: Version): self._uri = "/Flows" - def create( + def _create( self, friendly_name: str, status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, - ) -> FlowInstance: + author_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the FlowInstance - - :param friendly_name: The string that you assigned to describe the Flow. - :param status: - :param definition: JSON representation of flow definition. - :param commit_message: Description of change made in the revision. + Internal helper for create operation - :returns: The created FlowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -476,6 +770,7 @@ def create( "Status": status, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -484,29 +779,81 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return FlowInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> FlowInstance: """ - Asynchronously create the FlowInstance + Create the FlowInstance :param friendly_name: The string that you assigned to describe the Flow. :param status: :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. :returns: The created FlowInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the FlowInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -514,6 +861,7 @@ async def create_async( "Status": status, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -522,12 +870,67 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronously create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: The created FlowInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) return FlowInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the FlowInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -578,6 +981,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -597,6 +1050,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -623,6 +1077,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -631,6 +1086,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FlowInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -697,6 +1202,76 @@ async def page_async( ) return FlowPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> FlowPage: """ Retrieve a specific page of FlowInstance records from the API. diff --git a/twilio/rest/studio/v2/flow/execution/__init__.py b/twilio/rest/studio/v2/flow/execution/__init__.py index c47a3fbbc0..0a0bfa6fed 100644 --- a/twilio/rest/studio/v2/flow/execution/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,10 +36,13 @@ class Status(object): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. :ivar flow_sid: The SID of the Flow. :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar contact_sid: The SID of the Contact. + :ivar flow_version: The Flow version number at the time of Execution creation. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar status: :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar initiated_by: The SID or identifier that triggered this Execution. For example, a Call SID if triggered by an incoming call, a Message SID if triggered by an incoming message, a Request SID if triggered by a REST API request, and so on. :ivar url: The absolute URL of the resource. :ivar links: The URLs of nested resources. """ @@ -58,6 +62,10 @@ def __init__( self.contact_channel_address: Optional[str] = payload.get( "contact_channel_address" ) + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.flow_version: Optional[int] = deserialize.integer( + payload.get("flow_version") + ) self.context: Optional[Dict[str, object]] = payload.get("context") self.status: Optional["ExecutionInstance.Status"] = payload.get("status") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -66,6 +74,7 @@ def __init__( self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_updated") ) + self.initiated_by: Optional[str] = payload.get("initiated_by") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") @@ -73,6 +82,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionContext] = None @property @@ -109,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ExecutionInstance": """ Fetch the ExecutionInstance @@ -127,6 +155,24 @@ async def fetch_async(self) -> "ExecutionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ Update the ExecutionInstance @@ -153,6 +199,32 @@ async def update_async( status=status, ) + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def execution_context(self) -> ExecutionContextList: """ @@ -199,6 +271,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._execution_context: Optional[ExecutionContextList] = None self._steps: Optional[ExecutionStepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ExecutionInstance @@ -206,10 +292,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -218,27 +326,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ExecutionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ExecutionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = self._fetch() return ExecutionInstance( self._version, payload, @@ -246,22 +370,46 @@ def fetch(self) -> ExecutionInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ExecutionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionInstance + Fetch the ExecutionInstance and return response metadata - :returns: The fetched ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionInstance( self._version, payload, @@ -269,13 +417,28 @@ async def fetch_async(self) -> ExecutionInstance: sid=self._solution["sid"], ) - def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ExecutionInstance + Asynchronous coroutine to fetch the ExecutionInstance and return response metadata - :param status: - :returns: The updated ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -289,10 +452,19 @@ def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = self._update(status=status) return ExecutionInstance( self._version, payload, @@ -300,15 +472,29 @@ def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: sid=self._solution["sid"], ) - async def update_async( - self, status: "ExecutionInstance.Status" - ) -> ExecutionInstance: + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: """ - Asynchronous coroutine to update the ExecutionInstance + Update the ExecutionInstance and return response metadata :param status: - :returns: The updated ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "ExecutionInstance.Status") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -322,10 +508,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = await self._update_async(status=status) return ExecutionInstance( self._version, payload, @@ -333,6 +530,25 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def execution_context(self) -> ExecutionContextList: """ @@ -377,6 +593,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -408,17 +625,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> tuple: """ - Create the ExecutionInstance - - :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. - :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + Internal helper for create operation - :returns: The created ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -434,25 +648,55 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> ApiResponse: """ - Asynchronously create the ExecutionInstance + Create the ExecutionInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. - :returns: The created ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -468,16 +712,52 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ExecutionInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, limit: Optional[int] = None, @@ -489,6 +769,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param limit: Upper limit for the number of records to return. stream() @@ -502,6 +783,7 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( + status=status, date_created_from=date_created_from, date_created_to=date_created_to, page_size=limits["page_size"], @@ -511,6 +793,7 @@ def stream( async def stream_async( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, limit: Optional[int] = None, @@ -522,6 +805,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param limit: Upper limit for the number of records to return. stream() @@ -535,6 +819,7 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( + status=status, date_created_from=date_created_from, date_created_to=date_created_to, page_size=limits["page_size"], @@ -542,8 +827,79 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, limit: Optional[int] = None, @@ -554,6 +910,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param limit: Upper limit for the number of records to return. list() guarantees @@ -565,8 +922,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + status=status, date_created_from=date_created_from, date_created_to=date_created_to, limit=limit, @@ -576,6 +935,7 @@ def list( async def list_async( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, limit: Optional[int] = None, @@ -586,6 +946,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param limit: Upper limit for the number of records to return. list() guarantees @@ -597,9 +958,11 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + status=status, date_created_from=date_created_from, date_created_to=date_created_to, limit=limit, @@ -607,8 +970,77 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ExecutionInstance and returns headers from first page + + + :param "ExecutionInstance.Status" status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, page_token: Union[str, object] = values.unset, @@ -619,6 +1051,7 @@ def page( Retrieve a single page of ExecutionInstance records from the API. Request is executed immediately + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param page_token: PageToken provided by the API @@ -629,6 +1062,7 @@ def page( """ data = values.of( { + "status": status, "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), "DateCreatedTo": serialize.iso8601_datetime(date_created_to), "PageToken": page_token, @@ -644,10 +1078,11 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) async def page_async( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, page_token: Union[str, object] = values.unset, @@ -658,6 +1093,7 @@ async def page_async( Asynchronously retrieve a single page of ExecutionInstance records from the API. Request is executed immediately + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. :param page_token: PageToken provided by the API @@ -668,6 +1104,7 @@ async def page_async( """ data = values.of( { + "status": status, "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), "DateCreatedTo": serialize.iso8601_datetime(date_created_to), "PageToken": page_token, @@ -683,7 +1120,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["ExecutionInstance.Status", object] = values.unset, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Only show Execution resources with the given status. Can be: `active` or `ended`. + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionPage, status code, and headers + """ + data = values.of( + { + "status": status, + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ExecutionPage: """ @@ -695,7 +1220,7 @@ def get_page(self, target_url: str) -> ExecutionPage: :returns: Page of ExecutionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ExecutionPage: """ @@ -707,7 +1232,7 @@ async def get_page_async(self, target_url: str) -> ExecutionPage: :returns: Page of ExecutionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ExecutionPage(self._version, response, self._solution) + return ExecutionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ExecutionContext: """ diff --git a/twilio/rest/studio/v2/flow/execution/execution_context.py b/twilio/rest/studio/v2/flow/execution/execution_context.py index 4c18f81d11..d27773667f 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -84,6 +86,24 @@ async def fetch_async(self) -> "ExecutionContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,20 +135,30 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str): **self._solution ) - def fetch(self) -> ExecutionContextInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionContextInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + :returns: The fetched ExecutionContextInstance + """ + payload, _, _ = self._fetch() return ExecutionContextInstance( self._version, payload, @@ -136,22 +166,46 @@ def fetch(self) -> ExecutionContextInstance: execution_sid=self._solution["execution_sid"], ) - async def fetch_async(self) -> ExecutionContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionContextInstance + Fetch the ExecutionContextInstance and return response metadata - :returns: The fetched ExecutionContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionContextInstance( self._version, payload, @@ -159,6 +213,22 @@ async def fetch_async(self) -> ExecutionContextInstance: execution_sid=self._solution["execution_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py index b088aeab0e..57c14a8ab6 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,10 +32,12 @@ class ExecutionStepInstance(InstanceResource): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. :ivar flow_sid: The SID of the Flow. :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: The SID of the parent Step. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,10 +58,12 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.flow_sid: Optional[str] = payload.get("flow_sid") self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -73,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -110,6 +116,24 @@ async def fetch_async(self) -> "ExecutionStepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> ExecutionStepContextList: """ @@ -152,20 +176,30 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str self._step_context: Optional[ExecutionStepContextList] = None - def fetch(self) -> ExecutionStepInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionStepInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionStepInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + payload, _, _ = self._fetch() return ExecutionStepInstance( self._version, payload, @@ -174,22 +208,47 @@ def fetch(self) -> ExecutionStepInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ExecutionStepInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionStepInstance + Fetch the ExecutionStepInstance and return response metadata - :returns: The fetched ExecutionStepInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionStepInstance( self._version, payload, @@ -198,6 +257,23 @@ async def fetch_async(self) -> ExecutionStepInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def step_context(self) -> ExecutionStepContextList: """ @@ -230,6 +306,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -318,6 +395,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -337,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -363,6 +491,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -371,6 +500,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ExecutionStepInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -402,7 +581,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -435,7 +614,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionStepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ExecutionStepPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ExecutionStepPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ExecutionStepPage: """ @@ -447,7 +696,7 @@ def get_page(self, target_url: str) -> ExecutionStepPage: :returns: Page of ExecutionStepInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ExecutionStepPage: """ @@ -459,7 +708,7 @@ async def get_page_async(self, target_url: str) -> ExecutionStepPage: :returns: Page of ExecutionStepInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ExecutionStepPage(self._version, response, self._solution) + return ExecutionStepPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ExecutionStepContext: """ diff --git a/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py index 7f00e0d180..af826482f5 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "ExecutionStepContextInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -124,20 +144,30 @@ def __init__( **self._solution ) - def fetch(self) -> ExecutionStepContextInstance: + def _fetch(self) -> tuple: """ - Fetch the ExecutionStepContextInstance - + Internal helper for fetch operation - :returns: The fetched ExecutionStepContextInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + :returns: The fetched ExecutionStepContextInstance + """ + payload, _, _ = self._fetch() return ExecutionStepContextInstance( self._version, payload, @@ -146,22 +176,47 @@ def fetch(self) -> ExecutionStepContextInstance: step_sid=self._solution["step_sid"], ) - async def fetch_async(self) -> ExecutionStepContextInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ExecutionStepContextInstance + Fetch the ExecutionStepContextInstance and return response metadata - :returns: The fetched ExecutionStepContextInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + payload, _, _ = await self._fetch_async() return ExecutionStepContextInstance( self._version, payload, @@ -170,6 +225,23 @@ async def fetch_async(self) -> ExecutionStepContextInstance: step_sid=self._solution["step_sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v2/flow/flow_revision.py b/twilio/rest/studio/v2/flow/flow_revision.py index aa065074d1..046e08d7c6 100644 --- a/twilio/rest/studio/v2/flow/flow_revision.py +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class Status(object): """ :ivar sid: The unique string that we created to identify the Flow resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar author_sid: The SID of the User that created or last updated the Flow. :ivar friendly_name: The string that you assigned to describe the Flow. :ivar definition: JSON representation of flow definition. :ivar status: @@ -54,6 +56,7 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.account_sid: Optional[str] = payload.get("account_sid") + self.author_sid: Optional[str] = payload.get("author_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.definition: Optional[Dict[str, object]] = payload.get("definition") self.status: Optional["FlowRevisionInstance.Status"] = payload.get("status") @@ -73,6 +76,7 @@ def __init__( "sid": sid, "revision": revision or self.revision, } + self._context: Optional[FlowRevisionContext] = None @property @@ -109,6 +113,24 @@ async def fetch_async(self) -> "FlowRevisionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowRevisionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,20 +160,30 @@ def __init__(self, version: Version, sid: str, revision: str): } self._uri = "/Flows/{sid}/Revisions/{revision}".format(**self._solution) - def fetch(self) -> FlowRevisionInstance: + def _fetch(self) -> tuple: """ - Fetch the FlowRevisionInstance - + Internal helper for fetch operation - :returns: The fetched FlowRevisionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FlowRevisionInstance: + """ + Fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + payload, _, _ = self._fetch() return FlowRevisionInstance( self._version, payload, @@ -159,22 +191,46 @@ def fetch(self) -> FlowRevisionInstance: revision=self._solution["revision"], ) - async def fetch_async(self) -> FlowRevisionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlowRevisionInstance + Fetch the FlowRevisionInstance and return response metadata - :returns: The fetched FlowRevisionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlowRevisionInstance: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + payload, _, _ = await self._fetch_async() return FlowRevisionInstance( self._version, payload, @@ -182,6 +238,22 @@ async def fetch_async(self) -> FlowRevisionInstance: revision=self._solution["revision"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -200,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: :param payload: Payload response from the API """ + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) def __repr__(self) -> str: @@ -279,6 +352,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -298,6 +421,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -324,6 +448,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -332,6 +457,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FlowRevisionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -363,7 +538,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return FlowRevisionPage(self._version, response, self._solution) + return FlowRevisionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -396,7 +571,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return FlowRevisionPage(self._version, response, self._solution) + return FlowRevisionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowRevisionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FlowRevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FlowRevisionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FlowRevisionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> FlowRevisionPage: """ @@ -408,7 +653,7 @@ def get_page(self, target_url: str) -> FlowRevisionPage: :returns: Page of FlowRevisionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return FlowRevisionPage(self._version, response, self._solution) + return FlowRevisionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> FlowRevisionPage: """ @@ -420,7 +665,7 @@ async def get_page_async(self, target_url: str) -> FlowRevisionPage: :returns: Page of FlowRevisionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return FlowRevisionPage(self._version, response, self._solution) + return FlowRevisionPage(self._version, response, solution=self._solution) def get(self, revision: str) -> FlowRevisionContext: """ diff --git a/twilio/rest/studio/v2/flow/flow_test_user.py b/twilio/rest/studio/v2/flow/flow_test_user.py index cff41cd7e2..c030529dde 100644 --- a/twilio/rest/studio/v2/flow/flow_test_user.py +++ b/twilio/rest/studio/v2/flow/flow_test_user.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -37,6 +38,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[FlowTestUserContext] = None @property @@ -72,6 +74,24 @@ async def fetch_async(self) -> "FlowTestUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, test_users: List[str]) -> "FlowTestUserInstance": """ Update the FlowTestUserInstance @@ -96,6 +116,30 @@ async def update_async(self, test_users: List[str]) -> "FlowTestUserInstance": test_users=test_users, ) + def update_with_http_info(self, test_users: List[str]) -> ApiResponse: + """ + Update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + test_users=test_users, + ) + + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + test_users=test_users, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -123,55 +167,102 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Flows/{sid}/TestUsers".format(**self._solution) - def fetch(self) -> FlowTestUserInstance: + def _fetch(self) -> tuple: """ - Fetch the FlowTestUserInstance - + Internal helper for fetch operation - :returns: The fetched FlowTestUserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FlowTestUserInstance: + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + payload, _, _ = self._fetch() return FlowTestUserInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> FlowTestUserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FlowTestUserInstance + Fetch the FlowTestUserInstance and return response metadata - :returns: The fetched FlowTestUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FlowTestUserInstance: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + payload, _, _ = await self._fetch_async() return FlowTestUserInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, test_users: List[str]) -> FlowTestUserInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the FlowTestUserInstance + Asynchronous coroutine to fetch the FlowTestUserInstance and return response metadata - :param test_users: List of test user identities that can test draft versions of the flow. - :returns: The updated FlowTestUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, test_users: List[str]) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -185,19 +276,41 @@ def update(self, test_users: List[str]) -> FlowTestUserInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + payload, _, _ = self._update(test_users=test_users) return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async(self, test_users: List[str]) -> FlowTestUserInstance: + def update_with_http_info(self, test_users: List[str]) -> ApiResponse: """ - Asynchronous coroutine to update the FlowTestUserInstance + Update the FlowTestUserInstance and return response metadata :param test_users: List of test user identities that can test draft versions of the flow. - :returns: The updated FlowTestUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(test_users=test_users) + instance = FlowTestUserInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, test_users: List[str]) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -211,12 +324,35 @@ async def update_async(self, test_users: List[str]) -> FlowTestUserInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + payload, _, _ = await self._update_async(test_users=test_users) return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance and return response metadata + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(test_users=test_users) + instance = FlowTestUserInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v2/flow_validate.py b/twilio/rest/studio/v2/flow_validate.py index 5f8b308547..390ad74ca3 100644 --- a/twilio/rest/studio/v2/flow_validate.py +++ b/twilio/rest/studio/v2/flow_validate.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,22 +59,18 @@ def __init__(self, version: Version): self._uri = "/Flows/Validate" - def update( + def _update( self, friendly_name: str, status: "FlowValidateInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, - ) -> FlowValidateInstance: + ) -> tuple: """ - Update the FlowValidateInstance + Internal helper for update operation - :param friendly_name: The string that you assigned to describe the Flow. - :param status: - :param definition: JSON representation of flow definition. - :param commit_message: Description of change made in the revision. - - :returns: The created FlowValidateInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -90,28 +87,73 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowValidateInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) return FlowValidateInstance(self._version, payload) - async def update_async( + def update_with_http_info( self, friendly_name: str, status: "FlowValidateInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, - ) -> FlowValidateInstance: + ) -> ApiResponse: """ - Asynchronously update the FlowValidateInstance + Update the FlowValidateInstance and return response metadata :param friendly_name: The string that you assigned to describe the Flow. :param status: :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. - :returns: The created FlowValidateInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + instance = FlowValidateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -128,12 +170,61 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Asynchronously update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowValidateInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) return FlowValidateInstance(self._version, payload) + async def update_with_http_info_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously update the FlowValidateInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + instance = FlowValidateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/supersim/v1/esim_profile.py b/twilio/rest/supersim/v1/esim_profile.py index d12bb9b73f..f60d8f11d0 100644 --- a/twilio/rest/supersim/v1/esim_profile.py +++ b/twilio/rest/supersim/v1/esim_profile.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EsimProfileContext] = None @property @@ -111,6 +113,24 @@ async def fetch_async(self) -> "EsimProfileInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,48 +158,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/ESimProfiles/{sid}".format(**self._solution) - def fetch(self) -> EsimProfileInstance: + def _fetch(self) -> tuple: """ - Fetch the EsimProfileInstance + Internal helper for fetch operation - - :returns: The fetched EsimProfileInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> EsimProfileInstance: + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + payload, _, _ = self._fetch() return EsimProfileInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EsimProfileInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EsimProfileInstance + Fetch the EsimProfileInstance and return response metadata - :returns: The fetched EsimProfileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EsimProfileInstance: + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + payload, _, _ = await self._fetch_async() return EsimProfileInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EsimProfileInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +266,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EsimProfileInstance: :param payload: Payload response from the API """ + return EsimProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -222,22 +291,18 @@ def __init__(self, version: Version): self._uri = "/ESimProfiles" - def create( + def _create( self, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, generate_matching_id: Union[bool, object] = values.unset, eid: Union[str, object] = values.unset, - ) -> EsimProfileInstance: + ) -> tuple: """ - Create the EsimProfileInstance + Internal helper for create operation - :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. - :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. - :param eid: Identifier of the eUICC that will claim the eSIM Profile. - - :returns: The created EsimProfileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -254,13 +319,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return EsimProfileInstance(self._version, payload) - - async def create_async( + def create( self, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -268,7 +331,7 @@ async def create_async( eid: Union[str, object] = values.unset, ) -> EsimProfileInstance: """ - Asynchronously create the EsimProfileInstance + Create the EsimProfileInstance :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. @@ -277,6 +340,53 @@ async def create_async( :returns: The created EsimProfileInstance """ + payload, _, _ = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + return EsimProfileInstance(self._version, payload) + + def create_with_http_info( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the EsimProfileInstance and return response metadata + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -292,12 +402,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Asynchronously create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + payload, _, _ = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) return EsimProfileInstance(self._version, payload) + async def create_with_http_info_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EsimProfileInstance and return response metadata + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, eid: Union[str, object] = values.unset, @@ -364,6 +523,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EsimProfileInstance and returns headers from first page + + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EsimProfileInstance and returns headers from first page + + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, eid: Union[str, object] = values.unset, @@ -389,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( eid=eid, @@ -424,6 +648,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -435,6 +660,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EsimProfileInstance and returns headers from first page + + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EsimProfileInstance and returns headers from first page + + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, eid: Union[str, object] = values.unset, @@ -519,6 +812,94 @@ async def page_async( ) return EsimProfilePage(self._version, response) + def page_with_http_info( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EsimProfilePage, status code, and headers + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EsimProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EsimProfilePage, status code, and headers + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EsimProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EsimProfilePage: """ Retrieve a specific page of EsimProfileInstance records from the API. diff --git a/twilio/rest/supersim/v1/fleet.py b/twilio/rest/supersim/v1/fleet.py index 3ea067cff2..7f17059350 100644 --- a/twilio/rest/supersim/v1/fleet.py +++ b/twilio/rest/supersim/v1/fleet.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FleetContext] = None @property @@ -112,6 +114,24 @@ async def fetch_async(self) -> "FleetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FleetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FleetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -178,6 +198,72 @@ async def update_async( data_limit=data_limit, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FleetInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FleetInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -205,49 +291,97 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Fleets/{sid}".format(**self._solution) - def fetch(self) -> FleetInstance: + def _fetch(self) -> tuple: """ - Fetch the FleetInstance - + Internal helper for fetch operation - :returns: The fetched FleetInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FleetInstance: + """ + Fetch the FleetInstance + + :returns: The fetched FleetInstance + """ + payload, _, _ = self._fetch() return FleetInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> FleetInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FleetInstance + Fetch the FleetInstance and return response metadata - :returns: The fetched FleetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FleetInstance: + """ + Asynchronous coroutine to fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + payload, _, _ = await self._fetch_async() return FleetInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FleetInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, network_access_profile: Union[str, object] = values.unset, @@ -256,19 +390,12 @@ def update( sms_commands_url: Union[str, object] = values.unset, sms_commands_method: Union[str, object] = values.unset, data_limit: Union[int, object] = values.unset, - ) -> FleetInstance: + ) -> tuple: """ - Update the FleetInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. - :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. - :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. - :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + Internal helper for update operation - :returns: The updated FleetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -288,13 +415,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return FleetInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, network_access_profile: Union[str, object] = values.unset, @@ -305,7 +430,7 @@ async def update_async( data_limit: Union[int, object] = values.unset, ) -> FleetInstance: """ - Asynchronous coroutine to update the FleetInstance + Update the FleetInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. @@ -317,6 +442,68 @@ async def update_async( :returns: The updated FleetInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FleetInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + instance = FleetInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -335,12 +522,79 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronous coroutine to update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) return FleetInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FleetInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + instance = FleetInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -359,6 +613,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: :param payload: Payload response from the API """ + return FleetInstance(self._version, payload) def __repr__(self) -> str: @@ -383,7 +638,7 @@ def __init__(self, version: Version): self._uri = "/Fleets" - def create( + def _create( self, network_access_profile: str, unique_name: Union[str, object] = values.unset, @@ -394,21 +649,12 @@ def create( sms_commands_enabled: Union[bool, object] = values.unset, sms_commands_url: Union[str, object] = values.unset, sms_commands_method: Union[str, object] = values.unset, - ) -> FleetInstance: + ) -> tuple: """ - Create the FleetInstance - - :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. - :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). - :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. - :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. - :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + Internal helper for create operation - :returns: The created FleetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -430,13 +676,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return FleetInstance(self._version, payload) - - async def create_async( + def create( self, network_access_profile: str, unique_name: Union[str, object] = values.unset, @@ -449,7 +693,7 @@ async def create_async( sms_commands_method: Union[str, object] = values.unset, ) -> FleetInstance: """ - Asynchronously create the FleetInstance + Create the FleetInstance :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. @@ -463,8 +707,80 @@ async def create_async( :returns: The created FleetInstance """ - - data = values.of( + payload, _, _ = self._create( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + return FleetInstance(self._version, payload) + + def create_with_http_info( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the FleetInstance and return response metadata + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( { "NetworkAccessProfile": network_access_profile, "UniqueName": unique_name, @@ -483,12 +799,91 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronously create the FleetInstance + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: The created FleetInstance + """ + payload, _, _ = await self._create_async( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) return FleetInstance(self._version, payload) + async def create_with_http_info_async( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the FleetInstance and return response metadata + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + network_access_profile=network_access_profile, + unique_name=unique_name, + data_enabled=data_enabled, + data_limit=data_limit, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_enabled=sms_commands_enabled, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + ) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, network_access_profile: Union[str, object] = values.unset, @@ -547,6 +942,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, network_access_profile: Union[str, object] = values.unset, @@ -568,6 +1019,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( network_access_profile=network_access_profile, @@ -597,6 +1049,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -606,6 +1059,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FleetInstance and returns headers from first page + + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, network_access_profile: Union[str, object] = values.unset, @@ -678,6 +1187,82 @@ async def page_async( ) return FleetPage(self._version, response) + def page_with_http_info( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FleetPage, status code, and headers + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FleetPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FleetPage, status code, and headers + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FleetPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> FleetPage: """ Retrieve a specific page of FleetInstance records from the API. diff --git a/twilio/rest/supersim/v1/ip_command.py b/twilio/rest/supersim/v1/ip_command.py index 72bf78297f..2af10f7bfb 100644 --- a/twilio/rest/supersim/v1/ip_command.py +++ b/twilio/rest/supersim/v1/ip_command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[IpCommandContext] = None @property @@ -121,6 +123,24 @@ async def fetch_async(self) -> "IpCommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,48 +168,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/IpCommands/{sid}".format(**self._solution) - def fetch(self) -> IpCommandInstance: + def _fetch(self) -> tuple: """ - Fetch the IpCommandInstance - + Internal helper for fetch operation - :returns: The fetched IpCommandInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpCommandInstance: + """ + Fetch the IpCommandInstance + + :returns: The fetched IpCommandInstance + """ + payload, _, _ = self._fetch() return IpCommandInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> IpCommandInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpCommandInstance + Fetch the IpCommandInstance and return response metadata - :returns: The fetched IpCommandInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpCommandInstance: + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + payload, _, _ = await self._fetch_async() return IpCommandInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -208,6 +276,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpCommandInstance: :param payload: Payload response from the API """ + return IpCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -232,7 +301,7 @@ def __init__(self, version: Version): self._uri = "/IpCommands" - def create( + def _create( self, sim: str, payload: str, @@ -240,18 +309,12 @@ def create( payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, - ) -> IpCommandInstance: + ) -> tuple: """ - Create the IpCommandInstance + Internal helper for create operation - :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. - :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. - :param device_port: The device port to which the IP Command will be sent. - :param payload_type: - :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. - - :returns: The created IpCommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -270,13 +333,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return IpCommandInstance(self._version, payload) - - async def create_async( + def create( self, sim: str, payload: str, @@ -286,7 +347,7 @@ async def create_async( callback_method: Union[str, object] = values.unset, ) -> IpCommandInstance: """ - Asynchronously create the IpCommandInstance + Create the IpCommandInstance :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. @@ -297,6 +358,63 @@ async def create_async( :returns: The created IpCommandInstance """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + return IpCommandInstance(self._version, payload) + + def create_with_http_info( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the IpCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -314,12 +432,73 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Asynchronously create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) return IpCommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -398,6 +577,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -425,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -463,6 +719,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -475,6 +732,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -565,6 +896,100 @@ async def page_async( ) return IpCommandPage(self._version, response) + def page_with_http_info( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpCommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpCommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> IpCommandPage: """ Retrieve a specific page of IpCommandInstance records from the API. diff --git a/twilio/rest/supersim/v1/network.py b/twilio/rest/supersim/v1/network.py index 211068d075..c89787b807 100644 --- a/twilio/rest/supersim/v1/network.py +++ b/twilio/rest/supersim/v1/network.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "NetworkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,48 +126,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Networks/{sid}".format(**self._solution) - def fetch(self) -> NetworkInstance: + def _fetch(self) -> tuple: """ - Fetch the NetworkInstance - + Internal helper for fetch operation - :returns: The fetched NetworkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkInstance: + """ + Fetch the NetworkInstance + + :returns: The fetched NetworkInstance + """ + payload, _, _ = self._fetch() return NetworkInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> NetworkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NetworkInstance + Fetch the NetworkInstance and return response metadata - :returns: The fetched NetworkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + payload, _, _ = await self._fetch_async() return NetworkInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: :param payload: Payload response from the API """ + return NetworkInstance(self._version, payload) def __repr__(self) -> str: @@ -256,6 +325,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NetworkInstance and returns headers from first page + + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NetworkInstance and returns headers from first page + + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, iso_country: Union[str, object] = values.unset, @@ -281,6 +414,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_country=iso_country, @@ -316,6 +450,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -327,6 +462,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NetworkInstance and returns headers from first page + + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NetworkInstance and returns headers from first page + + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, iso_country: Union[str, object] = values.unset, @@ -411,6 +614,94 @@ async def page_async( ) return NetworkPage(self._version, response) + def page_with_http_info( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkPage, status code, and headers + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkPage, status code, and headers + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> NetworkPage: """ Retrieve a specific page of NetworkInstance records from the API. diff --git a/twilio/rest/supersim/v1/network_access_profile/__init__.py b/twilio/rest/supersim/v1/network_access_profile/__init__.py index 15b0cc5695..02c55897e5 100644 --- a/twilio/rest/supersim/v1/network_access_profile/__init__.py +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileContext] = None @property @@ -91,6 +93,24 @@ async def fetch_async(self) -> "NetworkAccessProfileInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset ) -> "NetworkAccessProfileInstance": @@ -119,6 +139,34 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + ) + @property def networks(self) -> NetworkAccessProfileNetworkList: """ @@ -155,57 +203,102 @@ def __init__(self, version: Version, sid: str): self._networks: Optional[NetworkAccessProfileNetworkList] = None - def fetch(self) -> NetworkAccessProfileInstance: + def _fetch(self) -> tuple: """ - Fetch the NetworkAccessProfileInstance + Internal helper for fetch operation - - :returns: The fetched NetworkAccessProfileInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileInstance: + """ + Fetch the NetworkAccessProfileInstance + + :returns: The fetched NetworkAccessProfileInstance + """ + payload, _, _ = self._fetch() return NetworkAccessProfileInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> NetworkAccessProfileInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NetworkAccessProfileInstance + Fetch the NetworkAccessProfileInstance and return response metadata - :returns: The fetched NetworkAccessProfileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + payload, _, _ = await self._fetch_async() return NetworkAccessProfileInstance( self._version, payload, sid=self._solution["sid"], ) - def update( - self, unique_name: Union[str, object] = values.unset - ) -> NetworkAccessProfileInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the NetworkAccessProfileInstance + Asynchronous coroutine to fetch the NetworkAccessProfileInstance and return response metadata - :param unique_name: The new unique name of the Network Access Profile. - :returns: The updated NetworkAccessProfileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, unique_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -219,23 +312,49 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + payload, _, _ = self._update(unique_name=unique_name) return NetworkAccessProfileInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, unique_name: Union[str, object] = values.unset - ) -> NetworkAccessProfileInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the NetworkAccessProfileInstance + Update the NetworkAccessProfileInstance and return response metadata :param unique_name: The new unique name of the Network Access Profile. - :returns: The updated NetworkAccessProfileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(unique_name=unique_name) + instance = NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, unique_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -249,14 +368,43 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + payload, _, _ = await self._update_async(unique_name=unique_name) return NetworkAccessProfileInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance and return response metadata + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name + ) + instance = NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def networks(self) -> NetworkAccessProfileNetworkList: """ @@ -287,6 +435,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: :param payload: Payload response from the API """ + return NetworkAccessProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -311,18 +460,16 @@ def __init__(self, version: Version): self._uri = "/NetworkAccessProfiles" - def create( + def _create( self, unique_name: Union[str, object] = values.unset, networks: Union[List[str], object] = values.unset, - ) -> NetworkAccessProfileInstance: + ) -> tuple: """ - Create the NetworkAccessProfileInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param networks: List of Network SIDs that this Network Access Profile will allow connections to. - - :returns: The created NetworkAccessProfileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -337,25 +484,56 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return NetworkAccessProfileInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, networks: Union[List[str], object] = values.unset, ) -> NetworkAccessProfileInstance: """ - Asynchronously create the NetworkAccessProfileInstance + Create the NetworkAccessProfileInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param networks: List of Network SIDs that this Network Access Profile will allow connections to. :returns: The created NetworkAccessProfileInstance """ + payload, _, _ = self._create(unique_name=unique_name, networks=networks) + return NetworkAccessProfileInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the NetworkAccessProfileInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -369,12 +547,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Asynchronously create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, networks=networks + ) return NetworkAccessProfileInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NetworkAccessProfileInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -425,6 +638,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -444,6 +707,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -470,6 +734,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -478,6 +743,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NetworkAccessProfileInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -544,6 +859,76 @@ async def page_async( ) return NetworkAccessProfilePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfilePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkAccessProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfilePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkAccessProfilePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> NetworkAccessProfilePage: """ Retrieve a specific page of NetworkAccessProfileInstance records from the API. diff --git a/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py index c7099b8a7a..7386d60751 100644 --- a/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py +++ b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "network_access_profile_sid": network_access_profile_sid, "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileNetworkContext] = None @property @@ -89,6 +91,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "NetworkAccessProfileNetworkInstance": """ Fetch the NetworkAccessProfileNetworkInstance @@ -107,6 +127,24 @@ async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,6 +180,20 @@ def __init__(self, version: Version, network_access_profile_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the NetworkAccessProfileNetworkInstance @@ -149,10 +201,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -161,27 +235,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> NetworkAccessProfileNetworkInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the NetworkAccessProfileNetworkInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched NetworkAccessProfileNetworkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileNetworkInstance: + """ + Fetch the NetworkAccessProfileNetworkInstance + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + payload, _, _ = self._fetch() return NetworkAccessProfileNetworkInstance( self._version, payload, @@ -189,22 +279,46 @@ def fetch(self) -> NetworkAccessProfileNetworkInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + Fetch the NetworkAccessProfileNetworkInstance and return response metadata - :returns: The fetched NetworkAccessProfileNetworkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + payload, _, _ = await self._fetch_async() return NetworkAccessProfileNetworkInstance( self._version, payload, @@ -212,6 +326,22 @@ async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -234,6 +364,7 @@ def get_instance( :param payload: Payload response from the API """ + return NetworkAccessProfileNetworkInstance( self._version, payload, @@ -271,13 +402,12 @@ def __init__(self, version: Version, network_access_profile_sid: str): ) ) - def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + def _create(self, network: str) -> tuple: """ - Create the NetworkAccessProfileNetworkInstance + Internal helper for create operation - :param network: The SID of the Network resource to be added to the Network Access Profile resource. - - :returns: The created NetworkAccessProfileNetworkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -291,23 +421,47 @@ def create(self, network: str) -> NetworkAccessProfileNetworkInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + payload, _, _ = self._create(network=network) return NetworkAccessProfileNetworkInstance( self._version, payload, network_access_profile_sid=self._solution["network_access_profile_sid"], ) - async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: + def create_with_http_info(self, network: str) -> ApiResponse: """ - Asynchronously create the NetworkAccessProfileNetworkInstance + Create the NetworkAccessProfileNetworkInstance and return response metadata :param network: The SID of the Network resource to be added to the Network Access Profile resource. - :returns: The created NetworkAccessProfileNetworkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(network=network) + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, network: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,16 +475,41 @@ async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstanc headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + payload, _, _ = await self._create_async(network=network) return NetworkAccessProfileNetworkInstance( self._version, payload, network_access_profile_sid=self._solution["network_access_profile_sid"], ) + async def create_with_http_info_async(self, network: str) -> ApiResponse: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance and return response metadata + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(network=network) + instance = NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -381,6 +560,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -400,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -426,6 +656,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -434,6 +665,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NetworkAccessProfileNetworkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -465,7 +746,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -498,7 +781,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: """ @@ -510,7 +869,9 @@ def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: :returns: Page of NetworkAccessProfileNetworkInstance """ response = self._version.domain.twilio.request("GET", target_url) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPage: """ @@ -522,7 +883,9 @@ async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPa :returns: Page of NetworkAccessProfileNetworkInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> NetworkAccessProfileNetworkContext: """ diff --git a/twilio/rest/supersim/v1/settings_update.py b/twilio/rest/supersim/v1/settings_update.py index 294e1102ce..8b6f2a03a7 100644 --- a/twilio/rest/supersim/v1/settings_update.py +++ b/twilio/rest/supersim/v1/settings_update.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SettingsUpdateInstance: :param payload: Payload response from the API """ + return SettingsUpdateInstance(self._version, payload) def __repr__(self) -> str: @@ -161,6 +163,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -184,6 +246,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -216,6 +279,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -226,6 +290,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -304,6 +430,88 @@ async def page_async( ) return SettingsUpdatePage(self._version, response) + def page_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SettingsUpdatePage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SettingsUpdatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SettingsUpdatePage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SettingsUpdatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SettingsUpdatePage: """ Retrieve a specific page of SettingsUpdateInstance records from the API. diff --git a/twilio/rest/supersim/v1/sim/__init__.py b/twilio/rest/supersim/v1/sim/__init__.py index fa878a16df..16f0046e17 100644 --- a/twilio/rest/supersim/v1/sim/__init__.py +++ b/twilio/rest/supersim/v1/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -109,6 +111,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -169,6 +189,66 @@ async def update_async( account_sid=account_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + @property def billing_periods(self) -> BillingPeriodList: """ @@ -213,49 +293,97 @@ def __init__(self, version: Version, sid: str): self._billing_periods: Optional[BillingPeriodList] = None self._sim_ip_addresses: Optional[SimIpAddressList] = None - def fetch(self) -> SimInstance: + def _fetch(self) -> tuple: """ - Fetch the SimInstance + Internal helper for fetch operation - - :returns: The fetched SimInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = self._fetch() return SimInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SimInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SimInstance + Fetch the SimInstance and return response metadata - :returns: The fetched SimInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = await self._fetch_async() return SimInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, status: Union["SimInstance.StatusUpdate", object] = values.unset, @@ -263,18 +391,12 @@ def update( callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> SimInstance: + ) -> tuple: """ - Update the SimInstance + Internal helper for update operation - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param status: - :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. - :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. - :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. - - :returns: The updated SimInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -293,13 +415,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SimInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, status: Union["SimInstance.StatusUpdate", object] = values.unset, @@ -309,7 +429,7 @@ async def update_async( account_sid: Union[str, object] = values.unset, ) -> SimInstance: """ - Asynchronous coroutine to update the SimInstance + Update the SimInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param status: @@ -320,6 +440,63 @@ async def update_async( :returns: The updated SimInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -337,12 +514,73 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) return SimInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def billing_periods(self) -> BillingPeriodList: """ @@ -385,6 +623,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -409,14 +648,12 @@ def __init__(self, version: Version): self._uri = "/Sims" - def create(self, iccid: str, registration_code: str) -> SimInstance: + def _create(self, iccid: str, registration_code: str) -> tuple: """ - Create the SimInstance + Internal helper for create operation - :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. - :param registration_code: The 10-digit code required to claim the Super SIM for your Account. - - :returns: The created SimInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -431,20 +668,43 @@ def create(self, iccid: str, registration_code: str) -> SimInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, iccid: str, registration_code: str) -> SimInstance: + """ + Create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + payload, _, _ = self._create(iccid=iccid, registration_code=registration_code) return SimInstance(self._version, payload) - async def create_async(self, iccid: str, registration_code: str) -> SimInstance: + def create_with_http_info(self, iccid: str, registration_code: str) -> ApiResponse: """ - Asynchronously create the SimInstance + Create the SimInstance and return response metadata :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. :param registration_code: The 10-digit code required to claim the Super SIM for your Account. - :returns: The created SimInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + iccid=iccid, registration_code=registration_code + ) + instance = SimInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, iccid: str, registration_code: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -459,12 +719,41 @@ async def create_async(self, iccid: str, registration_code: str) -> SimInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, iccid: str, registration_code: str) -> SimInstance: + """ + Asynchronously create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + payload, _, _ = await self._create_async( + iccid=iccid, registration_code=registration_code + ) return SimInstance(self._version, payload) + async def create_with_http_info_async( + self, iccid: str, registration_code: str + ) -> ApiResponse: + """ + Asynchronously create the SimInstance and return response metadata + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + iccid=iccid, registration_code=registration_code + ) + instance = SimInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["SimInstance.Status", object] = values.unset, @@ -531,6 +820,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["SimInstance.Status", object] = values.unset, @@ -556,6 +909,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -591,6 +945,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -602,6 +957,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["SimInstance.Status", object] = values.unset, @@ -686,6 +1109,94 @@ async def page_async( ) return SimPage(self._version, response) + def page_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SimPage: """ Retrieve a specific page of SimInstance records from the API. diff --git a/twilio/rest/supersim/v1/sim/billing_period.py b/twilio/rest/supersim/v1/sim/billing_period.py index 27cbe1222e..90a0e13d3d 100644 --- a/twilio/rest/supersim/v1/sim/billing_period.py +++ b/twilio/rest/supersim/v1/sim/billing_period.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BillingPeriodInstance: :param payload: Payload response from the API """ + return BillingPeriodInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -164,6 +166,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -183,6 +235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -209,6 +262,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -217,6 +271,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -248,7 +352,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BillingPeriodPage(self._version, response, self._solution) + return BillingPeriodPage(self._version, response, solution=self._solution) async def page_async( self, @@ -281,7 +385,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BillingPeriodPage(self._version, response, self._solution) + return BillingPeriodPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BillingPeriodPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BillingPeriodPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BillingPeriodPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BillingPeriodPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BillingPeriodPage: """ @@ -293,7 +467,7 @@ def get_page(self, target_url: str) -> BillingPeriodPage: :returns: Page of BillingPeriodInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BillingPeriodPage(self._version, response, self._solution) + return BillingPeriodPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BillingPeriodPage: """ @@ -305,7 +479,7 @@ async def get_page_async(self, target_url: str) -> BillingPeriodPage: :returns: Page of BillingPeriodInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BillingPeriodPage(self._version, response, self._solution) + return BillingPeriodPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/supersim/v1/sim/sim_ip_address.py b/twilio/rest/supersim/v1/sim/sim_ip_address.py index 0c4c3163b6..9d67476a36 100644 --- a/twilio/rest/supersim/v1/sim/sim_ip_address.py +++ b/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimIpAddressInstance: :param payload: Payload response from the API """ + return SimIpAddressInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -143,6 +145,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -162,6 +214,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -188,6 +241,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -196,6 +250,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -227,7 +331,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SimIpAddressPage(self._version, response, self._solution) + return SimIpAddressPage(self._version, response, solution=self._solution) async def page_async( self, @@ -260,7 +364,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SimIpAddressPage(self._version, response, self._solution) + return SimIpAddressPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimIpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimIpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimIpAddressPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimIpAddressPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SimIpAddressPage: """ @@ -272,7 +446,7 @@ def get_page(self, target_url: str) -> SimIpAddressPage: :returns: Page of SimIpAddressInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SimIpAddressPage(self._version, response, self._solution) + return SimIpAddressPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SimIpAddressPage: """ @@ -284,7 +458,7 @@ async def get_page_async(self, target_url: str) -> SimIpAddressPage: :returns: Page of SimIpAddressInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SimIpAddressPage(self._version, response, self._solution) + return SimIpAddressPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/supersim/v1/sms_command.py b/twilio/rest/supersim/v1/sms_command.py index dd70d2425e..3b4ce6558d 100644 --- a/twilio/rest/supersim/v1/sms_command.py +++ b/twilio/rest/supersim/v1/sms_command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SmsCommandContext] = None @property @@ -106,6 +108,24 @@ async def fetch_async(self) -> "SmsCommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -133,48 +153,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SmsCommands/{sid}".format(**self._solution) - def fetch(self) -> SmsCommandInstance: + def _fetch(self) -> tuple: """ - Fetch the SmsCommandInstance + Internal helper for fetch operation - - :returns: The fetched SmsCommandInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SmsCommandInstance: + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + payload, _, _ = self._fetch() return SmsCommandInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SmsCommandInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SmsCommandInstance + Fetch the SmsCommandInstance and return response metadata - :returns: The fetched SmsCommandInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SmsCommandInstance: + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + payload, _, _ = await self._fetch_async() return SmsCommandInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SmsCommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -193,6 +261,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SmsCommandInstance: :param payload: Payload response from the API """ + return SmsCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -217,22 +286,18 @@ def __init__(self, version: Version): self._uri = "/SmsCommands" - def create( + def _create( self, sim: str, payload: str, callback_method: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - ) -> SmsCommandInstance: + ) -> tuple: """ - Create the SmsCommandInstance + Internal helper for create operation - :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. - :param payload: The message body of the SMS Command. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. - :param callback_url: The URL we should call using the `callback_method` after we have sent the command. - - :returns: The created SmsCommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -249,13 +314,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SmsCommandInstance(self._version, payload) - - async def create_async( + def create( self, sim: str, payload: str, @@ -263,7 +326,7 @@ async def create_async( callback_url: Union[str, object] = values.unset, ) -> SmsCommandInstance: """ - Asynchronously create the SmsCommandInstance + Create the SmsCommandInstance :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. :param payload: The message body of the SMS Command. @@ -272,6 +335,53 @@ async def create_async( :returns: The created SmsCommandInstance """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + return SmsCommandInstance(self._version, payload) + + def create_with_http_info( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the SmsCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -287,12 +397,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Asynchronously create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) return SmsCommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SmsCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -359,6 +518,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SmsCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SmsCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -384,6 +607,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -419,6 +643,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -430,6 +655,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SmsCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SmsCommandInstance and returns headers from first page + + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -514,6 +807,94 @@ async def page_async( ) return SmsCommandPage(self._version, response) + def page_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SmsCommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SmsCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SmsCommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SmsCommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SmsCommandPage: """ Retrieve a specific page of SmsCommandInstance records from the API. diff --git a/twilio/rest/supersim/v1/usage_record.py b/twilio/rest/supersim/v1/usage_record.py index 94072a51fb..05547f6d64 100644 --- a/twilio/rest/supersim/v1/usage_record.py +++ b/twilio/rest/supersim/v1/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -210,6 +212,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -245,6 +347,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -295,6 +398,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +415,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -425,6 +627,124 @@ async def page_async( ) return UsageRecordPage(self._version, response) + def page_with_http_info( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> UsageRecordPage: """ Retrieve a specific page of UsageRecordInstance records from the API. diff --git a/twilio/rest/sync/v1/service/__init__.py b/twilio/rest/sync/v1/service/__init__.py index d17491d3cb..a376ed7982 100644 --- a/twilio/rest/sync/v1/service/__init__.py +++ b/twilio/rest/sync/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, webhook_url: Union[str, object] = values.unset, @@ -198,6 +236,72 @@ async def update_async( webhooks_from_rest_enabled=webhooks_from_rest_enabled, ) + def update_with_http_info( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + async def update_with_http_info_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + @property def documents(self) -> DocumentList: """ @@ -258,6 +362,20 @@ def __init__(self, version: Version, sid: str): self._sync_maps: Optional[SyncMapList] = None self._sync_streams: Optional[SyncStreamList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -265,10 +383,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -277,56 +417,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, webhook_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -335,19 +529,12 @@ def update( reachability_debouncing_enabled: Union[bool, object] = values.unset, reachability_debouncing_window: Union[int, object] = values.unset, webhooks_from_rest_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance + Internal helper for update operation - :param webhook_url: The URL we should call when Sync objects are manipulated. - :param friendly_name: A string that you assign to describe the resource. - :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. - :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. - :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. - :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. - :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. - - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -373,13 +560,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, webhook_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -390,7 +575,7 @@ async def update_async( webhooks_from_rest_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param webhook_url: The URL we should call when Sync objects are manipulated. :param friendly_name: A string that you assign to describe the resource. @@ -402,6 +587,68 @@ async def update_async( :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -426,11 +673,78 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property def documents(self) -> DocumentList: @@ -498,6 +812,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -522,7 +837,7 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, webhook_url: Union[str, object] = values.unset, @@ -531,19 +846,12 @@ def create( reachability_debouncing_enabled: Union[bool, object] = values.unset, reachability_debouncing_window: Union[int, object] = values.unset, webhooks_from_rest_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A string that you assign to describe the resource. - :param webhook_url: The URL we should call when Sync objects are manipulated. - :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. - :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. - :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. - :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. - :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -569,13 +877,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset, webhook_url: Union[str, object] = values.unset, @@ -586,7 +892,7 @@ async def create_async( webhooks_from_rest_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param friendly_name: A string that you assign to describe the resource. :param webhook_url: The URL we should call when Sync objects are manipulated. @@ -598,6 +904,68 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -622,12 +990,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -678,6 +1113,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -697,6 +1182,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -723,6 +1209,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -731,6 +1218,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -797,6 +1334,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/sync/v1/service/document/__init__.py b/twilio/rest/sync/v1/service/document/__init__.py index fe64f629a8..3611fe0d18 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[DocumentContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DocumentInstance": """ Fetch the DocumentInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "DocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -169,6 +207,48 @@ async def update_async( ttl=ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the DocumentInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + ) + @property def document_permissions(self) -> DocumentPermissionList: """ @@ -207,6 +287,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._document_permissions: Optional[DocumentPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DocumentInstance @@ -214,10 +308,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -226,27 +342,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> DocumentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the DocumentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched DocumentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentInstance: + """ + Fetch the DocumentInstance + + :returns: The fetched DocumentInstance + """ + payload, _, _ = self._fetch() return DocumentInstance( self._version, payload, @@ -254,22 +386,46 @@ def fetch(self) -> DocumentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> DocumentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DocumentInstance + Fetch the DocumentInstance and return response metadata - :returns: The fetched DocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DocumentInstance: + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + payload, _, _ = await self._fetch_async() return DocumentInstance( self._version, payload, @@ -277,20 +433,33 @@ async def fetch_async(self) -> DocumentInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> tuple: """ - Update the DocumentInstance - - :param if_match: The If-Match HTTP request header - :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + Internal helper for update operation - :returns: The updated DocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,10 +479,26 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + payload, _, _ = self._update(if_match=if_match, data=data, ttl=ttl) return DocumentInstance( self._version, payload, @@ -321,20 +506,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the DocumentInstance + Update the DocumentInstance and return response metadata :param if_match: The If-Match HTTP request header :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). - :returns: The updated DocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -354,10 +562,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + payload, _, _ = await self._update_async(if_match=if_match, data=data, ttl=ttl) return DocumentInstance( self._version, payload, @@ -365,6 +589,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def document_permissions(self) -> DocumentPermissionList: """ @@ -396,6 +646,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: :param payload: Payload response from the API """ + return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -427,20 +678,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Documents".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> tuple: """ - Create the DocumentInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the Sync Document - :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). - - :returns: The created DocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -456,28 +704,64 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + payload, _, _ = self._create(unique_name=unique_name, data=data, ttl=ttl) return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> ApiResponse: """ - Asynchronously create the DocumentInstance + Create the DocumentInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the Sync Document :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). - :returns: The created DocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,14 +777,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronously create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the DocumentInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -551,6 +876,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -570,6 +945,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,6 +972,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -604,6 +981,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -635,7 +1062,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DocumentPage(self._version, response, self._solution) + return DocumentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -668,7 +1095,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DocumentPage(self._version, response, self._solution) + return DocumentPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DocumentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DocumentPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DocumentPage: """ @@ -680,7 +1177,7 @@ def get_page(self, target_url: str) -> DocumentPage: :returns: Page of DocumentInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DocumentPage(self._version, response, self._solution) + return DocumentPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DocumentPage: """ @@ -692,7 +1189,7 @@ async def get_page_async(self, target_url: str) -> DocumentPage: :returns: Page of DocumentInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DocumentPage(self._version, response, self._solution) + return DocumentPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DocumentContext: """ diff --git a/twilio/rest/sync/v1/service/document/document_permission.py b/twilio/rest/sync/v1/service/document/document_permission.py index 75a27c969a..16f87b9cd1 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "document_sid": document_sid, "identity": identity or self.identity, } + self._context: Optional[DocumentPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DocumentPermissionInstance": """ Fetch the DocumentPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "DocumentPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "DocumentPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the DocumentPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -183,6 +257,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DocumentPermissionInstance @@ -190,10 +278,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -202,27 +312,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> DocumentPermissionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the DocumentPermissionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched DocumentPermissionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentPermissionInstance: + """ + Fetch the DocumentPermissionInstance + + :returns: The fetched DocumentPermissionInstance + """ + payload, _, _ = self._fetch() return DocumentPermissionInstance( self._version, payload, @@ -231,22 +357,47 @@ def fetch(self) -> DocumentPermissionInstance: identity=self._solution["identity"], ) - async def fetch_async(self) -> DocumentPermissionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the DocumentPermissionInstance + Fetch the DocumentPermissionInstance and return response metadata - :returns: The fetched DocumentPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + payload, _, _ = await self._fetch_async() return DocumentPermissionInstance( self._version, payload, @@ -255,17 +406,29 @@ async def fetch_async(self) -> DocumentPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the DocumentPermissionInstance + Asynchronous coroutine to fetch the DocumentPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync Document. Default value is `false`. - :param write: Whether the identity can update the Sync Document. Default value is `false`. - :param manage: Whether the identity can delete the Sync Document. Default value is `false`. - :returns: The updated DocumentPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,10 +444,23 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return DocumentPermissionInstance( self._version, payload, @@ -293,17 +469,36 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the DocumentPermissionInstance + Update the DocumentPermissionInstance and return response metadata :param read: Whether the identity can read the Sync Document. Default value is `false`. :param write: Whether the identity can update the Sync Document. Default value is `false`. :param manage: Whether the identity can delete the Sync Document. Default value is `false`. - :returns: The updated DocumentPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -319,10 +514,23 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return DocumentPermissionInstance( self._version, payload, @@ -331,6 +539,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -349,6 +581,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: :param payload: Payload response from the API """ + return DocumentPermissionInstance( self._version, payload, @@ -439,6 +672,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -458,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -484,6 +768,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -492,6 +777,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DocumentPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -523,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DocumentPermissionPage(self._version, response, self._solution) + return DocumentPermissionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -556,7 +891,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DocumentPermissionPage(self._version, response, self._solution) + return DocumentPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DocumentPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DocumentPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DocumentPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DocumentPermissionPage: """ @@ -568,7 +973,7 @@ def get_page(self, target_url: str) -> DocumentPermissionPage: :returns: Page of DocumentPermissionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DocumentPermissionPage(self._version, response, self._solution) + return DocumentPermissionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DocumentPermissionPage: """ @@ -580,7 +985,7 @@ async def get_page_async(self, target_url: str) -> DocumentPermissionPage: :returns: Page of DocumentPermissionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DocumentPermissionPage(self._version, response, self._solution) + return DocumentPermissionPage(self._version, response, solution=self._solution) def get(self, identity: str) -> DocumentPermissionContext: """ diff --git a/twilio/rest/sync/v1/service/sync_list/__init__.py b/twilio/rest/sync/v1/service/sync_list/__init__.py index 1b8e54aff8..e757173ab9 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncListContext] = None @property @@ -108,6 +110,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncListInstance": """ Fetch the SyncListInstance @@ -126,6 +146,24 @@ async def fetch_async(self) -> "SyncListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ttl: Union[int, object] = values.unset, @@ -162,6 +200,42 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + @property def sync_list_items(self) -> SyncListItemList: """ @@ -208,6 +282,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._sync_list_items: Optional[SyncListItemList] = None self._sync_list_permissions: Optional[SyncListPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncListInstance @@ -215,10 +303,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -227,27 +337,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SyncListInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SyncListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SyncListInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListInstance: + """ + Fetch the SyncListInstance + + :returns: The fetched SyncListInstance + """ + payload, _, _ = self._fetch() return SyncListInstance( self._version, payload, @@ -255,22 +381,46 @@ def fetch(self) -> SyncListInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SyncListInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncListInstance + Fetch the SyncListInstance and return response metadata - :returns: The fetched SyncListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncListInstance: + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + payload, _, _ = await self._fetch_async() return SyncListInstance( self._version, payload, @@ -278,18 +428,32 @@ async def fetch_async(self) -> SyncListInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> tuple: """ - Update the SyncListInstance + Internal helper for update operation - :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. - - :returns: The updated SyncListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -304,10 +468,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + payload, _, _ = self._update(ttl=ttl, collection_ttl=collection_ttl) return SyncListInstance( self._version, payload, @@ -315,18 +493,40 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncListInstance + Update the SyncListInstance and return response metadata :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. - :returns: The updated SyncListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -341,10 +541,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + payload, _, _ = await self._update_async(ttl=ttl, collection_ttl=collection_ttl) return SyncListInstance( self._version, payload, @@ -352,6 +566,30 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListInstance and return response metadata + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def sync_list_items(self) -> SyncListItemList: """ @@ -396,6 +634,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: :param payload: Payload response from the API """ + return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -427,20 +666,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Lists".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> tuple: """ - Create the SyncListInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -456,28 +692,66 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncListInstance + Create the SyncListInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. - :returns: The created SyncListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,14 +767,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronously create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncListInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -551,6 +866,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -570,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,6 +962,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -604,6 +971,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -635,7 +1052,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListPage(self._version, response, self._solution) + return SyncListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -668,7 +1085,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListPage(self._version, response, self._solution) + return SyncListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncListPage: """ @@ -680,7 +1167,7 @@ def get_page(self, target_url: str) -> SyncListPage: :returns: Page of SyncListInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncListPage(self._version, response, self._solution) + return SyncListPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncListPage: """ @@ -692,7 +1179,7 @@ async def get_page_async(self, target_url: str) -> SyncListPage: :returns: Page of SyncListInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListPage(self._version, response, self._solution) + return SyncListPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SyncListContext: """ diff --git a/twilio/rest/sync/v1/service/sync_list/sync_list_item.py b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py index 61783aa525..40dfcbadf9 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_item.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "list_sid": list_sid, "index": index or self.index, } + self._context: Optional[SyncListItemContext] = None @property @@ -122,6 +124,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "SyncListItemInstance": """ Fetch the SyncListItemInstance @@ -140,6 +170,24 @@ async def fetch_async(self) -> "SyncListItemInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -194,6 +242,60 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -227,13 +329,12 @@ def __init__(self, version: Version, service_sid: str, list_sid: str, index: int **self._solution ) - def delete(self, if_match: Union[str, object] = values.unset) -> bool: + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Deletes the SyncListItemInstance - - :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + Internal helper for delete operation - :returns: True if delete succeeds, False otherwise + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of( { @@ -243,16 +344,41 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Asynchronous coroutine that deletes the SyncListItemInstance + Deletes the SyncListItemInstance :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncListItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "If-Match": if_match, @@ -261,24 +387,58 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo headers = values.of({}) - return await self._version.delete_async( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers ) - def fetch(self) -> SyncListItemInstance: + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Fetch the SyncListItemInstance + Asynchronous coroutine that deletes the SyncListItemInstance + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :returns: The fetched SyncListItemInstance + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(if_match=if_match) + return success + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListItemInstance: + """ + Fetch the SyncListItemInstance + + :returns: The fetched SyncListItemInstance + """ + payload, _, _ = self._fetch() return SyncListItemInstance( self._version, payload, @@ -287,22 +447,47 @@ def fetch(self) -> SyncListItemInstance: index=self._solution["index"], ) - async def fetch_async(self) -> SyncListItemInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncListItemInstance + Fetch the SyncListItemInstance and return response metadata - :returns: The fetched SyncListItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncListItemInstance: + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + payload, _, _ = await self._fetch_async() return SyncListItemInstance( self._version, payload, @@ -311,24 +496,36 @@ async def fetch_async(self) -> SyncListItemInstance: index=self._solution["index"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListItemInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> tuple: """ - Update the SyncListItemInstance - - :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + Internal helper for update operation - :returns: The updated SyncListItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -350,10 +547,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) return SyncListItemInstance( self._version, payload, @@ -362,16 +585,16 @@ def update( index=self._solution["index"], ) - async def update_async( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncListItemInstance + Update the SyncListItemInstance and return response metadata :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. @@ -379,7 +602,37 @@ async def update_async( :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. - :returns: The updated SyncListItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -401,17 +654,78 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - - return SyncListItemInstance( + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncListItemInstance( self._version, payload, service_sid=self._solution["service_sid"], list_sid=self._solution["list_sid"], index=self._solution["index"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -431,6 +745,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: :param payload: Payload response from the API """ + return SyncListItemInstance( self._version, payload, @@ -469,22 +784,18 @@ def __init__(self, version: Version, service_sid: str, list_sid: str): **self._solution ) - def create( + def _create( self, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> tuple: """ - Create the SyncListItemInstance - - :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncListItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -501,10 +812,30 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + payload, _, _ = self._create( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) return SyncListItemInstance( self._version, payload, @@ -512,22 +843,46 @@ def create( list_sid=self._solution["list_sid"], ) - async def create_async( + def create_with_http_info( self, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncListItemInstance + Create the SyncListItemInstance and return response metadata :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. - :returns: The created SyncListItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -544,10 +899,30 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronously create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + payload, _, _ = await self._create_async( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) return SyncListItemInstance( self._version, payload, @@ -555,6 +930,34 @@ async def create_async( list_sid=self._solution["list_sid"], ) + async def create_with_http_info_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncListItemInstance and return response metadata + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, @@ -621,6 +1024,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncListItemInstance and returns headers from first page + + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncListItemInstance and returns headers from first page + + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, @@ -646,6 +1113,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -681,6 +1149,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -692,6 +1161,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncListItemInstance and returns headers from first page + + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncListItemInstance and returns headers from first page + + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, @@ -732,7 +1269,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListItemPage(self._version, response, self._solution) + return SyncListItemPage(self._version, response, solution=self._solution) async def page_async( self, @@ -774,7 +1311,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListItemPage(self._version, response, self._solution) + return SyncListItemPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListItemPage, status code, and headers + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListItemPage, status code, and headers + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncListItemPage: """ @@ -786,7 +1411,7 @@ def get_page(self, target_url: str) -> SyncListItemPage: :returns: Page of SyncListItemInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncListItemPage(self._version, response, self._solution) + return SyncListItemPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncListItemPage: """ @@ -798,7 +1423,7 @@ async def get_page_async(self, target_url: str) -> SyncListItemPage: :returns: Page of SyncListItemInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListItemPage(self._version, response, self._solution) + return SyncListItemPage(self._version, response, solution=self._solution) def get(self, index: int) -> SyncListItemContext: """ diff --git a/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py index f1eb853468..620954de44 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "list_sid": list_sid, "identity": identity or self.identity, } + self._context: Optional[SyncListPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncListPermissionInstance": """ Fetch the SyncListPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "SyncListPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "SyncListPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncListPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -185,6 +259,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncListPermissionInstance @@ -192,10 +280,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -204,27 +314,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SyncListPermissionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SyncListPermissionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SyncListPermissionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListPermissionInstance: + """ + Fetch the SyncListPermissionInstance + + :returns: The fetched SyncListPermissionInstance + """ + payload, _, _ = self._fetch() return SyncListPermissionInstance( self._version, payload, @@ -233,22 +359,47 @@ def fetch(self) -> SyncListPermissionInstance: identity=self._solution["identity"], ) - async def fetch_async(self) -> SyncListPermissionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncListPermissionInstance + Fetch the SyncListPermissionInstance and return response metadata - :returns: The fetched SyncListPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + payload, _, _ = await self._fetch_async() return SyncListPermissionInstance( self._version, payload, @@ -257,17 +408,29 @@ async def fetch_async(self) -> SyncListPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SyncListPermissionInstance + Asynchronous coroutine to fetch the SyncListPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. - :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. - :param manage: Whether the identity can delete the Sync List. Default value is `false`. - :returns: The updated SyncListPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -283,10 +446,23 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return SyncListPermissionInstance( self._version, payload, @@ -295,17 +471,36 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncListPermissionInstance + Update the SyncListPermissionInstance and return response metadata :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. :param manage: Whether the identity can delete the Sync List. Default value is `false`. - :returns: The updated SyncListPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,10 +516,23 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncListPermissionInstance( self._version, payload, @@ -333,6 +541,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -351,6 +583,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: :param payload: Payload response from the API """ + return SyncListPermissionInstance( self._version, payload, @@ -439,6 +672,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -458,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -484,6 +768,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -492,6 +777,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncListPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -523,7 +858,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListPermissionPage(self._version, response, self._solution) + return SyncListPermissionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -556,7 +891,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncListPermissionPage(self._version, response, self._solution) + return SyncListPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncListPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncListPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncListPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncListPermissionPage: """ @@ -568,7 +973,7 @@ def get_page(self, target_url: str) -> SyncListPermissionPage: :returns: Page of SyncListPermissionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncListPermissionPage(self._version, response, self._solution) + return SyncListPermissionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncListPermissionPage: """ @@ -580,7 +985,7 @@ async def get_page_async(self, target_url: str) -> SyncListPermissionPage: :returns: Page of SyncListPermissionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncListPermissionPage(self._version, response, self._solution) + return SyncListPermissionPage(self._version, response, solution=self._solution) def get(self, identity: str) -> SyncListPermissionContext: """ diff --git a/twilio/rest/sync/v1/service/sync_map/__init__.py b/twilio/rest/sync/v1/service/sync_map/__init__.py index c6bb1ce556..1c5049b798 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncMapContext] = None @property @@ -108,6 +110,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncMapInstance": """ Fetch the SyncMapInstance @@ -126,6 +146,24 @@ async def fetch_async(self) -> "SyncMapInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ttl: Union[int, object] = values.unset, @@ -162,6 +200,42 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + @property def sync_map_items(self) -> SyncMapItemList: """ @@ -208,6 +282,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._sync_map_items: Optional[SyncMapItemList] = None self._sync_map_permissions: Optional[SyncMapPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncMapInstance @@ -215,10 +303,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -227,27 +337,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SyncMapInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SyncMapInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SyncMapInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapInstance: + """ + Fetch the SyncMapInstance + + :returns: The fetched SyncMapInstance + """ + payload, _, _ = self._fetch() return SyncMapInstance( self._version, payload, @@ -255,22 +381,46 @@ def fetch(self) -> SyncMapInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SyncMapInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncMapInstance + Fetch the SyncMapInstance and return response metadata - :returns: The fetched SyncMapInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncMapInstance: + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + payload, _, _ = await self._fetch_async() return SyncMapInstance( self._version, payload, @@ -278,18 +428,32 @@ async def fetch_async(self) -> SyncMapInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> tuple: """ - Update the SyncMapInstance + Internal helper for update operation - :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. - - :returns: The updated SyncMapInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -304,10 +468,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + payload, _, _ = self._update(ttl=ttl, collection_ttl=collection_ttl) return SyncMapInstance( self._version, payload, @@ -315,18 +493,40 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncMapInstance + Update the SyncMapInstance and return response metadata :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. - :returns: The updated SyncMapInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -341,10 +541,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + payload, _, _ = await self._update_async(ttl=ttl, collection_ttl=collection_ttl) return SyncMapInstance( self._version, payload, @@ -352,6 +566,30 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapInstance and return response metadata + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def sync_map_items(self) -> SyncMapItemList: """ @@ -396,6 +634,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: :param payload: Payload response from the API """ + return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -427,20 +666,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Maps".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> tuple: """ - Create the SyncMapInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncMapInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -456,28 +692,66 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncMapInstance + Create the SyncMapInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. - :returns: The created SyncMapInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,14 +767,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronously create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncMapInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -551,6 +866,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncMapInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncMapInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -570,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,6 +962,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -604,6 +971,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncMapInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncMapInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -635,7 +1052,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapPage(self._version, response, self._solution) + return SyncMapPage(self._version, response, solution=self._solution) async def page_async( self, @@ -668,7 +1085,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapPage(self._version, response, self._solution) + return SyncMapPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncMapPage: """ @@ -680,7 +1167,7 @@ def get_page(self, target_url: str) -> SyncMapPage: :returns: Page of SyncMapInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncMapPage(self._version, response, self._solution) + return SyncMapPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncMapPage: """ @@ -692,7 +1179,7 @@ async def get_page_async(self, target_url: str) -> SyncMapPage: :returns: Page of SyncMapInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapPage(self._version, response, self._solution) + return SyncMapPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SyncMapContext: """ diff --git a/twilio/rest/sync/v1/service/sync_map/sync_map_item.py b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py index 4939694026..e63720c278 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_item.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "map_sid": map_sid, "key": key or self.key, } + self._context: Optional[SyncMapItemContext] = None @property @@ -122,6 +124,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "SyncMapItemInstance": """ Fetch the SyncMapItemInstance @@ -140,6 +170,24 @@ async def fetch_async(self) -> "SyncMapItemInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -194,6 +242,60 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -227,13 +329,12 @@ def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): **self._solution ) - def delete(self, if_match: Union[str, object] = values.unset) -> bool: + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Deletes the SyncMapItemInstance - - :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + Internal helper for delete operation - :returns: True if delete succeeds, False otherwise + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of( { @@ -243,16 +344,41 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Asynchronous coroutine that deletes the SyncMapItemInstance + Deletes the SyncMapItemInstance :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncMapItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "If-Match": if_match, @@ -261,24 +387,58 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo headers = values.of({}) - return await self._version.delete_async( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers ) - def fetch(self) -> SyncMapItemInstance: + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Fetch the SyncMapItemInstance + Asynchronous coroutine that deletes the SyncMapItemInstance + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :returns: The fetched SyncMapItemInstance + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(if_match=if_match) + return success + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapItemInstance: + """ + Fetch the SyncMapItemInstance + + :returns: The fetched SyncMapItemInstance + """ + payload, _, _ = self._fetch() return SyncMapItemInstance( self._version, payload, @@ -287,22 +447,47 @@ def fetch(self) -> SyncMapItemInstance: key=self._solution["key"], ) - async def fetch_async(self) -> SyncMapItemInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncMapItemInstance + Fetch the SyncMapItemInstance and return response metadata - :returns: The fetched SyncMapItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncMapItemInstance: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + payload, _, _ = await self._fetch_async() return SyncMapItemInstance( self._version, payload, @@ -311,24 +496,36 @@ async def fetch_async(self) -> SyncMapItemInstance: key=self._solution["key"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapItemInstance: + ) -> tuple: """ - Update the SyncMapItemInstance + Internal helper for update operation - :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. - - :returns: The updated SyncMapItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -350,10 +547,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) return SyncMapItemInstance( self._version, payload, @@ -362,16 +585,16 @@ def update( key=self._solution["key"], ) - async def update_async( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapItemInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncMapItemInstance + Update the SyncMapItemInstance and return response metadata :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. @@ -379,7 +602,37 @@ async def update_async( :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. - :returns: The updated SyncMapItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -401,10 +654,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) return SyncMapItemInstance( self._version, payload, @@ -413,24 +692,60 @@ async def update_async( key=self._solution["key"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Sync.V1.SyncMapItemContext {}>".format(context) + Asynchronous coroutine to update the SyncMapItemInstance and return response metadata + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. -class SyncMapItemPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapItemContext {}>".format(context) + + +class SyncMapItemPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: """ Build an instance of SyncMapItemInstance :param payload: Payload response from the API """ + return SyncMapItemInstance( self._version, payload, @@ -469,24 +784,19 @@ def __init__(self, version: Version, service_sid: str, map_sid: str): **self._solution ) - def create( + def _create( self, key: str, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapItemInstance: + ) -> tuple: """ - Create the SyncMapItemInstance + Internal helper for create operation - :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. - :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. - - :returns: The created SyncMapItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -504,10 +814,36 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + payload, _, _ = self._create( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) return SyncMapItemInstance( self._version, payload, @@ -515,16 +851,16 @@ def create( map_sid=self._solution["map_sid"], ) - async def create_async( + def create_with_http_info( self, key: str, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapItemInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncMapItemInstance + Create the SyncMapItemInstance and return response metadata :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. @@ -532,7 +868,36 @@ async def create_async( :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. - :returns: The created SyncMapItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -550,10 +915,36 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronously create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + payload, _, _ = await self._create_async( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) return SyncMapItemInstance( self._version, payload, @@ -561,6 +952,40 @@ async def create_async( map_sid=self._solution["map_sid"], ) + async def create_with_http_info_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncMapItemInstance and return response metadata + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, @@ -627,6 +1052,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncMapItemInstance and returns headers from first page + + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncMapItemInstance and returns headers from first page + + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, @@ -652,6 +1141,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -687,6 +1177,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -698,6 +1189,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncMapItemInstance and returns headers from first page + + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncMapItemInstance and returns headers from first page + + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, @@ -738,7 +1297,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapItemPage(self._version, response, self._solution) + return SyncMapItemPage(self._version, response, solution=self._solution) async def page_async( self, @@ -780,7 +1339,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapItemPage(self._version, response, self._solution) + return SyncMapItemPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapItemPage, status code, and headers + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapItemPage, status code, and headers + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapItemPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncMapItemPage: """ @@ -792,7 +1439,7 @@ def get_page(self, target_url: str) -> SyncMapItemPage: :returns: Page of SyncMapItemInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncMapItemPage(self._version, response, self._solution) + return SyncMapItemPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncMapItemPage: """ @@ -804,7 +1451,7 @@ async def get_page_async(self, target_url: str) -> SyncMapItemPage: :returns: Page of SyncMapItemInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapItemPage(self._version, response, self._solution) + return SyncMapItemPage(self._version, response, solution=self._solution) def get(self, key: str) -> SyncMapItemContext: """ diff --git a/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py index 910560add0..eb210e017b 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "map_sid": map_sid, "identity": identity or self.identity, } + self._context: Optional[SyncMapPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncMapPermissionInstance": """ Fetch the SyncMapPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "SyncMapPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "SyncMapPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncMapPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -183,6 +257,20 @@ def __init__(self, version: Version, service_sid: str, map_sid: str, identity: s ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncMapPermissionInstance @@ -190,10 +278,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapPermissionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -202,27 +312,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SyncMapPermissionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SyncMapPermissionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SyncMapPermissionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapPermissionInstance: + """ + Fetch the SyncMapPermissionInstance + + :returns: The fetched SyncMapPermissionInstance + """ + payload, _, _ = self._fetch() return SyncMapPermissionInstance( self._version, payload, @@ -231,22 +357,47 @@ def fetch(self) -> SyncMapPermissionInstance: identity=self._solution["identity"], ) - async def fetch_async(self) -> SyncMapPermissionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncMapPermissionInstance + Fetch the SyncMapPermissionInstance and return response metadata - :returns: The fetched SyncMapPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + payload, _, _ = await self._fetch_async() return SyncMapPermissionInstance( self._version, payload, @@ -255,17 +406,29 @@ async def fetch_async(self) -> SyncMapPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SyncMapPermissionInstance + Asynchronous coroutine to fetch the SyncMapPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. - :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. - :param manage: Whether the identity can delete the Sync Map. Default value is `false`. - :returns: The updated SyncMapPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,10 +444,23 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return SyncMapPermissionInstance( self._version, payload, @@ -293,17 +469,36 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncMapPermissionInstance + Update the SyncMapPermissionInstance and return response metadata :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. :param manage: Whether the identity can delete the Sync Map. Default value is `false`. - :returns: The updated SyncMapPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -319,10 +514,23 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncMapPermissionInstance( self._version, payload, @@ -331,6 +539,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -349,6 +581,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: :param payload: Payload response from the API """ + return SyncMapPermissionInstance( self._version, payload, @@ -437,6 +670,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -456,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -482,6 +766,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -490,6 +775,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncMapPermissionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -521,7 +856,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapPermissionPage(self._version, response, self._solution) + return SyncMapPermissionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -554,7 +889,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncMapPermissionPage(self._version, response, self._solution) + return SyncMapPermissionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncMapPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncMapPermissionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncMapPermissionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncMapPermissionPage: """ @@ -566,7 +971,7 @@ def get_page(self, target_url: str) -> SyncMapPermissionPage: :returns: Page of SyncMapPermissionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncMapPermissionPage(self._version, response, self._solution) + return SyncMapPermissionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: """ @@ -578,7 +983,7 @@ async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: :returns: Page of SyncMapPermissionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncMapPermissionPage(self._version, response, self._solution) + return SyncMapPermissionPage(self._version, response, solution=self._solution) def get(self, identity: str) -> SyncMapPermissionContext: """ diff --git a/twilio/rest/sync/v1/service/sync_stream/__init__.py b/twilio/rest/sync/v1/service/sync_stream/__init__.py index a7f4128e05..f233231d44 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncStreamContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncStreamInstance": """ Fetch the SyncStreamInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "SyncStreamInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": """ Update the SyncStreamInstance @@ -147,6 +185,34 @@ async def update_async( ttl=ttl, ) + def update_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SyncStreamInstance with HTTP info + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + ) + + async def update_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncStreamInstance with HTTP info + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + ) + @property def stream_messages(self) -> StreamMessageList: """ @@ -185,6 +251,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._stream_messages: Optional[StreamMessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncStreamInstance @@ -192,10 +272,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncStreamInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -204,27 +306,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SyncStreamInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SyncStreamInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SyncStreamInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncStreamInstance: + """ + Fetch the SyncStreamInstance + + :returns: The fetched SyncStreamInstance + """ + payload, _, _ = self._fetch() return SyncStreamInstance( self._version, payload, @@ -232,22 +350,46 @@ def fetch(self) -> SyncStreamInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SyncStreamInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SyncStreamInstance + Fetch the SyncStreamInstance and return response metadata - :returns: The fetched SyncStreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SyncStreamInstance: + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + payload, _, _ = await self._fetch_async() return SyncStreamInstance( self._version, payload, @@ -255,13 +397,28 @@ async def fetch_async(self) -> SyncStreamInstance: sid=self._solution["sid"], ) - def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SyncStreamInstance + Asynchronous coroutine to fetch the SyncStreamInstance and return response metadata - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - :returns: The updated SyncStreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -275,10 +432,19 @@ def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: + """ + Update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + payload, _, _ = self._update(ttl=ttl) return SyncStreamInstance( self._version, payload, @@ -286,15 +452,31 @@ def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, ttl: Union[int, object] = values.unset - ) -> SyncStreamInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncStreamInstance + Update the SyncStreamInstance and return response metadata :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - :returns: The updated SyncStreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(ttl=ttl) + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +490,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> SyncStreamInstance: + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + payload, _, _ = await self._update_async(ttl=ttl) return SyncStreamInstance( self._version, payload, @@ -319,6 +512,25 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncStreamInstance and return response metadata + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(ttl=ttl) + instance = SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def stream_messages(self) -> StreamMessageList: """ @@ -350,6 +562,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: :param payload: Payload response from the API """ + return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -381,18 +594,16 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Streams".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> SyncStreamInstance: + ) -> tuple: """ - Create the SyncStreamInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + Internal helper for create operation - :returns: The created SyncStreamInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -407,26 +618,57 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + payload, _, _ = self._create(unique_name=unique_name, ttl=ttl) return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> SyncStreamInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncStreamInstance + Create the SyncStreamInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - :returns: The created SyncStreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(unique_name=unique_name, ttl=ttl) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -441,14 +683,49 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Asynchronously create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + payload, _, _ = await self._create_async(unique_name=unique_name, ttl=ttl) return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncStreamInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl + ) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -499,6 +776,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SyncStreamInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SyncStreamInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -518,6 +845,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -544,6 +872,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -552,6 +881,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SyncStreamInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SyncStreamInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -583,7 +962,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncStreamPage(self._version, response, self._solution) + return SyncStreamPage(self._version, response, solution=self._solution) async def page_async( self, @@ -616,7 +995,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SyncStreamPage(self._version, response, self._solution) + return SyncStreamPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncStreamPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SyncStreamPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SyncStreamPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SyncStreamPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SyncStreamPage: """ @@ -628,7 +1077,7 @@ def get_page(self, target_url: str) -> SyncStreamPage: :returns: Page of SyncStreamInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SyncStreamPage(self._version, response, self._solution) + return SyncStreamPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SyncStreamPage: """ @@ -640,7 +1089,7 @@ async def get_page_async(self, target_url: str) -> SyncStreamPage: :returns: Page of SyncStreamInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SyncStreamPage(self._version, response, self._solution) + return SyncStreamPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SyncStreamContext: """ diff --git a/twilio/rest/sync/v1/service/sync_stream/stream_message.py b/twilio/rest/sync/v1/service/sync_stream/stream_message.py index bcce239975..f7646d1936 100644 --- a/twilio/rest/sync/v1/service/sync_stream/stream_message.py +++ b/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,13 +76,12 @@ def __init__(self, version: Version, service_sid: str, stream_sid: str): **self._solution ) - def create(self, data: object) -> StreamMessageInstance: + def _create(self, data: object) -> tuple: """ - Create the StreamMessageInstance - - :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + Internal helper for create operation - :returns: The created StreamMessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -95,10 +95,19 @@ def create(self, data: object) -> StreamMessageInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, data: object) -> StreamMessageInstance: + """ + Create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + payload, _, _ = self._create(data=data) return StreamMessageInstance( self._version, payload, @@ -106,13 +115,29 @@ def create(self, data: object) -> StreamMessageInstance: stream_sid=self._solution["stream_sid"], ) - async def create_async(self, data: object) -> StreamMessageInstance: + def create_with_http_info(self, data: object) -> ApiResponse: """ - Asynchronously create the StreamMessageInstance + Create the StreamMessageInstance and return response metadata :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. - :returns: The created StreamMessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(data=data) + instance = StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, data: object) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -126,10 +151,19 @@ async def create_async(self, data: object) -> StreamMessageInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, data: object) -> StreamMessageInstance: + """ + Asynchronously create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + payload, _, _ = await self._create_async(data=data) return StreamMessageInstance( self._version, payload, @@ -137,6 +171,23 @@ async def create_async(self, data: object) -> StreamMessageInstance: stream_sid=self._solution["stream_sid"], ) + async def create_with_http_info_async(self, data: object) -> ApiResponse: + """ + Asynchronously create the StreamMessageInstance and return response metadata + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(data=data) + instance = StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/__init__.py b/twilio/rest/taskrouter/v1/workspace/__init__.py index 086e3e1747..5e857c3d0a 100644 --- a/twilio/rest/taskrouter/v1/workspace/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -92,6 +93,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[WorkspaceContext] = None @property @@ -127,6 +129,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WorkspaceInstance": """ Fetch the WorkspaceInstance @@ -145,6 +165,24 @@ async def fetch_async(self) -> "WorkspaceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_activity_sid: Union[str, object] = values.unset, @@ -215,6 +253,76 @@ async def update_async( prioritize_queue_order=prioritize_queue_order, ) + def update_with_http_info( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the WorkspaceInstance with HTTP info + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + async def update_with_http_info_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance with HTTP info + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + @property def activities(self) -> ActivityList: """ @@ -323,6 +431,20 @@ def __init__(self, version: Version, sid: str): self._real_time_statistics: Optional[WorkspaceRealTimeStatisticsList] = None self._statistics: Optional[WorkspaceStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WorkspaceInstance @@ -330,10 +452,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkspaceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -342,56 +486,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkspaceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WorkspaceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WorkspaceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WorkspaceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkspaceInstance: + """ + Fetch the WorkspaceInstance + + :returns: The fetched WorkspaceInstance + """ + payload, _, _ = self._fetch() return WorkspaceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> WorkspaceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkspaceInstance + Fetch the WorkspaceInstance and return response metadata - :returns: The fetched WorkspaceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WorkspaceInstance: + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + payload, _, _ = await self._fetch_async() return WorkspaceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, default_activity_sid: Union[str, object] = values.unset, event_callback_url: Union[str, object] = values.unset, @@ -402,19 +600,12 @@ def update( prioritize_queue_order: Union[ "WorkspaceInstance.QueueOrder", object ] = values.unset, - ) -> WorkspaceInstance: + ) -> tuple: """ - Update the WorkspaceInstance - - :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. - :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). - :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. - :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. - :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). - :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. - :param prioritize_queue_order: + Internal helper for update operation - :returns: The updated WorkspaceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -434,13 +625,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, default_activity_sid: Union[str, object] = values.unset, event_callback_url: Union[str, object] = values.unset, @@ -453,7 +642,7 @@ async def update_async( ] = values.unset, ) -> WorkspaceInstance: """ - Asynchronous coroutine to update the WorkspaceInstance + Update the WorkspaceInstance :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). @@ -465,6 +654,72 @@ async def update_async( :returns: The updated WorkspaceInstance """ + payload, _, _ = self._update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the WorkspaceInstance and return response metadata + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -483,31 +738,102 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def activities(self) -> ActivityList: - """ - Access the activities + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: """ - if self._activities is None: - self._activities = ActivityList( - self._version, - self._solution["sid"], - ) - return self._activities + Asynchronous coroutine to update the WorkspaceInstance - @property - def events(self) -> EventList: - """ - Access the events + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance """ - if self._events is None: - self._events = EventList( + payload, _, _ = await self._update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance and return response metadata + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + if self._activities is None: + self._activities = ActivityList( + self._version, + self._solution["sid"], + ) + return self._activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( self._version, self._solution["sid"], ) @@ -627,6 +953,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: :param payload: Payload response from the API """ + return WorkspaceInstance(self._version, payload) def __repr__(self) -> str: @@ -651,7 +978,7 @@ def __init__(self, version: Version): self._uri = "/Workspaces" - def create( + def _create( self, friendly_name: str, event_callback_url: Union[str, object] = values.unset, @@ -661,18 +988,12 @@ def create( prioritize_queue_order: Union[ "WorkspaceInstance.QueueOrder", object ] = values.unset, - ) -> WorkspaceInstance: + ) -> tuple: """ - Create the WorkspaceInstance - - :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. - :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). - :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. - :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). - :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. - :param prioritize_queue_order: + Internal helper for create operation - :returns: The created WorkspaceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -691,13 +1012,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return WorkspaceInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, event_callback_url: Union[str, object] = values.unset, @@ -709,7 +1028,7 @@ async def create_async( ] = values.unset, ) -> WorkspaceInstance: """ - Asynchronously create the WorkspaceInstance + Create the WorkspaceInstance :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). @@ -720,6 +1039,67 @@ async def create_async( :returns: The created WorkspaceInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -737,12 +1117,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronously create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) return WorkspaceInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -799,6 +1244,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WorkspaceInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WorkspaceInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -820,6 +1321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -849,6 +1351,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -858,6 +1361,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WorkspaceInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WorkspaceInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -930,6 +1489,82 @@ async def page_async( ) return WorkspacePage(self._version, response) + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkspacePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkspacePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkspacePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkspacePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> WorkspacePage: """ Retrieve a specific page of WorkspaceInstance records from the API. diff --git a/twilio/rest/taskrouter/v1/workspace/activity.py b/twilio/rest/taskrouter/v1/workspace/activity.py index 4e3e416af7..580948aa5c 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[ActivityContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ActivityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ActivityInstance": """ Fetch the ActivityInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "ActivityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActivityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActivityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "ActivityInstance": @@ -144,6 +182,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ActivityInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ActivityInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -175,6 +241,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ActivityInstance @@ -182,10 +262,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ActivityInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -194,27 +296,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ActivityInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ActivityInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ActivityInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ActivityInstance: + """ + Fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + payload, _, _ = self._fetch() return ActivityInstance( self._version, payload, @@ -222,22 +340,46 @@ def fetch(self) -> ActivityInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ActivityInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ActivityInstance + Fetch the ActivityInstance and return response metadata - :returns: The fetched ActivityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ActivityInstance: + """ + Asynchronous coroutine to fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + payload, _, _ = await self._fetch_async() return ActivityInstance( self._version, payload, @@ -245,15 +387,28 @@ async def fetch_async(self) -> ActivityInstance: sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> ActivityInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ActivityInstance + Asynchronous coroutine to fetch the ActivityInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. - :returns: The updated ActivityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -267,10 +422,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return ActivityInstance( self._version, payload, @@ -278,15 +444,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> ActivityInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ActivityInstance + Update the ActivityInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. - :returns: The updated ActivityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -300,10 +484,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return ActivityInstance( self._version, payload, @@ -311,6 +506,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ActivityInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -329,6 +545,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: :param payload: Payload response from the API """ + return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -360,16 +577,14 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) - def create( + def _create( self, friendly_name: str, available: Union[bool, object] = values.unset - ) -> ActivityInstance: + ) -> tuple: """ - Create the ActivityInstance - - :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. - :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + Internal helper for create operation - :returns: The created ActivityInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -384,24 +599,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name, available=available) return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, available: Union[bool, object] = values.unset - ) -> ActivityInstance: + ) -> ApiResponse: """ - Asynchronously create the ActivityInstance + Create the ActivityInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. - :returns: The created ActivityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -416,14 +660,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronously create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, available=available + ) return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ActivityInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -490,6 +767,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ActivityInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ActivityInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -513,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -545,6 +887,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -555,6 +898,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ActivityInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ActivityInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -592,7 +997,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ActivityPage(self._version, response, self._solution) + return ActivityPage(self._version, response, solution=self._solution) async def page_async( self, @@ -631,7 +1036,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ActivityPage(self._version, response, self._solution) + return ActivityPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ActivityPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ActivityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ActivityPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ActivityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ActivityPage: """ @@ -643,7 +1130,7 @@ def get_page(self, target_url: str) -> ActivityPage: :returns: Page of ActivityInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ActivityPage(self._version, response, self._solution) + return ActivityPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ActivityPage: """ @@ -655,7 +1142,7 @@ async def get_page_async(self, target_url: str) -> ActivityPage: :returns: Page of ActivityInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ActivityPage(self._version, response, self._solution) + return ActivityPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ActivityContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/event.py b/twilio/rest/taskrouter/v1/workspace/event.py index 1b7f289e5e..73cc6f2ebf 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -112,6 +114,24 @@ async def fetch_async(self) -> "EventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,20 +161,30 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): } self._uri = "/Workspaces/{workspace_sid}/Events/{sid}".format(**self._solution) - def fetch(self) -> EventInstance: + def _fetch(self) -> tuple: """ - Fetch the EventInstance - + Internal helper for fetch operation - :returns: The fetched EventInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + :returns: The fetched EventInstance + """ + payload, _, _ = self._fetch() return EventInstance( self._version, payload, @@ -162,22 +192,46 @@ def fetch(self) -> EventInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> EventInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EventInstance + Fetch the EventInstance and return response metadata - :returns: The fetched EventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + payload, _, _ = await self._fetch_async() return EventInstance( self._version, payload, @@ -185,6 +239,22 @@ async def fetch_async(self) -> EventInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +273,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -354,6 +425,124 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end_date: Union[datetime, object] = values.unset, @@ -395,6 +584,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_date=end_date, @@ -454,6 +644,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -473,6 +664,122 @@ async def list_async( ) ] + def list_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end_date: Union[datetime, object] = values.unset, @@ -537,7 +844,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -603,7 +910,143 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EventPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EventPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EventPage: """ @@ -615,7 +1058,7 @@ def get_page(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EventPage: """ @@ -627,7 +1070,7 @@ async def get_page_async(self, target_url: str) -> EventPage: :returns: Page of EventInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EventPage(self._version, response, self._solution) + return EventPage(self._version, response, solution=self._solution) def get(self, sid: str) -> EventContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/task/__init__.py b/twilio/rest/taskrouter/v1/workspace/task/__init__.py index 2c4516df77..c03fe1abb9 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -114,6 +115,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskContext] = None @property @@ -156,6 +158,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the TaskInstance with HTTP info + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskInstance with HTTP info + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "TaskInstance": """ Fetch the TaskInstance @@ -174,6 +204,24 @@ async def fetch_async(self) -> "TaskInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -240,6 +288,72 @@ async def update_async( virtual_start_time=virtual_start_time, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + @property def reservations(self) -> ReservationList: """ @@ -278,13 +392,12 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._reservations: Optional[ReservationList] = None - def delete(self, if_match: Union[str, object] = values.unset) -> bool: + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Deletes the TaskInstance - - :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + Internal helper for delete operation - :returns: True if delete succeeds, False otherwise + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of( { @@ -294,16 +407,41 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Asynchronous coroutine that deletes the TaskInstance + Deletes the TaskInstance :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the TaskInstance and return response metadata + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "If-Match": if_match, @@ -312,24 +450,58 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo headers = values.of({}) - return await self._version.delete_async( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers ) - def fetch(self) -> TaskInstance: + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Fetch the TaskInstance + Asynchronous coroutine that deletes the TaskInstance + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :returns: The fetched TaskInstance + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(if_match=if_match) + return success + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskInstance and return response metadata + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskInstance: + """ + Fetch the TaskInstance + + :returns: The fetched TaskInstance + """ + payload, _, _ = self._fetch() return TaskInstance( self._version, payload, @@ -337,22 +509,46 @@ def fetch(self) -> TaskInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TaskInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskInstance + Fetch the TaskInstance and return response metadata - :returns: The fetched TaskInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TaskInstance: + """ + Asynchronous coroutine to fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + payload, _, _ = await self._fetch_async() return TaskInstance( self._version, payload, @@ -360,7 +556,23 @@ async def fetch_async(self) -> TaskInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, @@ -369,19 +581,12 @@ def update( priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, virtual_start_time: Union[datetime, object] = values.unset, - ) -> TaskInstance: + ) -> tuple: """ - Update the TaskInstance - - :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :param attributes: The JSON string that describes the custom attributes of the task. - :param assignment_status: - :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. - :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). - :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + Internal helper for update operation - :returns: The updated TaskInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -405,10 +610,42 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + payload, _, _ = self._update( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) return TaskInstance( self._version, payload, @@ -416,7 +653,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, @@ -425,9 +662,9 @@ async def update_async( priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, virtual_start_time: Union[datetime, object] = values.unset, - ) -> TaskInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TaskInstance + Update the TaskInstance and return response metadata :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :param attributes: The JSON string that describes the custom attributes of the task. @@ -437,7 +674,40 @@ async def update_async( :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. - :returns: The updated TaskInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -461,26 +731,98 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return TaskInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - sid=self._solution["sid"], - ) - - @property - def reservations(self) -> ReservationList: - """ - Access the reservations + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: """ - if self._reservations is None: - self._reservations = ReservationList( - self._version, - self._solution["workspace_sid"], + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + instance = TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], self._solution["sid"], ) return self._reservations @@ -503,6 +845,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: :param payload: Payload response from the API """ + return TaskInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -534,7 +877,7 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Tasks".format(**self._solution) - def create( + def _create( self, timeout: Union[int, object] = values.unset, priority: Union[int, object] = values.unset, @@ -545,21 +888,12 @@ def create( routing_target: Union[str, object] = values.unset, ignore_capacity: Union[str, object] = values.unset, task_queue_sid: Union[str, object] = values.unset, - ) -> TaskInstance: + ) -> tuple: """ - Create the TaskInstance + Internal helper for create operation - :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. - :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). - :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. - :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. - :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. - :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. - :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to - :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. - :param task_queue_sid: The SID of the TaskQueue in which the Task belongs - - :returns: The created TaskInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -581,15 +915,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + payload, _, _ = self._create( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) return TaskInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, timeout: Union[int, object] = values.unset, priority: Union[int, object] = values.unset, @@ -600,21 +972,55 @@ async def create_async( routing_target: Union[str, object] = values.unset, ignore_capacity: Union[str, object] = values.unset, task_queue_sid: Union[str, object] = values.unset, - ) -> TaskInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskInstance + Create the TaskInstance and return response metadata :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. - :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. :param task_queue_sid: The SID of the TaskQueue in which the Task belongs - :returns: The created TaskInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + instance = TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -636,15 +1042,210 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronously create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + payload, _, _ = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskInstance and return response metadata + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + instance = TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: + """ + Streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskInstance]: + """ + Asynchronously streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], ) - return TaskInstance( - self._version, payload, workspace_sid=self._solution["workspace_sid"] - ) + return self._version.stream_async(page, limits["limit"]) - def stream( + def stream_with_http_info( self, priority: Union[int, object] = values.unset, assignment_status: Union[List[str], object] = values.unset, @@ -658,12 +1259,10 @@ def stream( has_addons: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, - ) -> Iterator[TaskInstance]: + ) -> tuple: """ - Streams TaskInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Streams TaskInstance and returns headers from first page + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. @@ -682,10 +1281,10 @@ def stream( but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results + :returns: tuple of (generator, status_code, headers) where generator yields instances """ limits = self._version.read_limits(limit, page_size) - page = self.page( + page_response = self.page_with_http_info( priority=priority, assignment_status=assignment_status, workflow_sid=workflow_sid, @@ -699,9 +1298,10 @@ def stream( page_size=limits["page_size"], ) - return self._version.stream(page, limits["limit"]) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - async def stream_async( + async def stream_with_http_info_async( self, priority: Union[int, object] = values.unset, assignment_status: Union[List[str], object] = values.unset, @@ -715,12 +1315,10 @@ async def stream_async( has_addons: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, - ) -> AsyncIterator[TaskInstance]: + ) -> tuple: """ - Asynchronously streams TaskInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Asynchronously streams TaskInstance and returns headers from first page + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. @@ -739,10 +1337,10 @@ async def stream_async( but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results + :returns: tuple of (generator, status_code, headers) where generator yields instances """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async( + page_response = await self.page_with_http_info_async( priority=priority, assignment_status=assignment_status, workflow_sid=workflow_sid, @@ -756,7 +1354,8 @@ async def stream_async( page_size=limits["page_size"], ) - return self._version.stream_async(page, limits["limit"]) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) def list( self, @@ -797,6 +1396,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( priority=priority, @@ -853,6 +1453,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -871,6 +1472,116 @@ async def list_async( ) ] + def list_with_http_info( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TaskInstance and returns headers from first page + + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TaskInstance and returns headers from first page + + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, priority: Union[int, object] = values.unset, @@ -932,7 +1643,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskPage(self._version, response, self._solution) + return TaskPage(self._version, response, solution=self._solution) async def page_async( self, @@ -995,7 +1706,137 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskPage(self._version, response, self._solution) + return TaskPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskPage, status code, and headers + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskPage, status code, and headers + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TaskPage: """ @@ -1007,7 +1848,7 @@ def get_page(self, target_url: str) -> TaskPage: :returns: Page of TaskInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TaskPage(self._version, response, self._solution) + return TaskPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TaskPage: """ @@ -1019,7 +1860,7 @@ async def get_page_async(self, target_url: str) -> TaskPage: :returns: Page of TaskInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskPage(self._version, response, self._solution) + return TaskPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TaskContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/task/reservation.py b/twilio/rest/taskrouter/v1/workspace/task/reservation.py index 5318543ea2..c6a845b47b 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( "task_sid": task_sid, "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None @property @@ -138,6 +140,24 @@ async def fetch_async(self) -> "ReservationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -250,7 +270,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -433,7 +453,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -504,88 +524,7 @@ async def update_async( jitter_buffer_size=jitter_buffer_size, ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) - - -class ReservationContext(InstanceContext): - - def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): - """ - Initialize the ReservationContext - - :param version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the TaskReservation resources to update. - :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to update. - :param sid: The SID of the TaskReservation resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "workspace_sid": workspace_sid, - "task_sid": task_sid, - "sid": sid, - } - self._uri = ( - "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}".format( - **self._solution - ) - ) - - def fetch(self) -> ReservationInstance: - """ - Fetch the ReservationInstance - - - :returns: The fetched ReservationInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ReservationInstance: - """ - Asynchronous coroutine to fetch the ReservationInstance - - - :returns: The fetched ReservationInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -648,9 +587,9 @@ def update( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -697,7 +636,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -708,105 +647,67 @@ def update( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "CallUrl": call_url, - "CallStatusCallbackUrl": call_status_callback_url, - "CallAccept": serialize.boolean_to_string(call_accept), - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": serialize.boolean_to_string(redirect_accept), - "RedirectUrl": redirect_url, - "To": to, - "From": from_, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "Timeout": timeout, - "Record": serialize.boolean_to_string(record), - "Muted": serialize.boolean_to_string(muted), - "Beep": beep, - "StartConferenceOnEnter": serialize.boolean_to_string( - start_conference_on_enter - ), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": serialize.boolean_to_string(early_media), - "MaxParticipants": max_participants, - "ConferenceStatusCallback": conference_status_callback, - "ConferenceStatusCallbackMethod": conference_status_callback_method, - "ConferenceStatusCallbackEvent": serialize.map( - conference_status_callback_event, lambda e: e - ), - "ConferenceRecord": conference_record, - "ConferenceTrim": conference_trim, - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "ConferenceRecordingStatusCallback": conference_recording_status_callback, - "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, - "Region": region, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "DequeueStatusCallbackEvent": serialize.map( - dequeue_status_callback_event, lambda e: e - ), - "PostWorkActivitySid": post_work_activity_sid, - "SupervisorMode": supervisor_mode, - "Supervisor": supervisor, - "EndConferenceOnCustomerExit": serialize.boolean_to_string( - end_conference_on_customer_exit - ), - "BeepOnCustomerEntrance": serialize.boolean_to_string( - beep_on_customer_entrance - ), - "JitterBufferSize": jitter_buffer_size, - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], + return self._proxy.update_with_http_info( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, ) - async def update_async( + async def update_with_http_info_async( self, if_match: Union[str, object] = values.unset, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -869,9 +770,9 @@ async def update_async( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ReservationInstance + Asynchronous coroutine to update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -918,7 +819,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -929,18 +830,279 @@ async def update_async( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, + return await self._proxy.update_with_http_info_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to update. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to update. + :param sid: The SID of the TaskReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}".format( + **self._solution + ) + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = self._fetch() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = await self._fetch_async() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, "DequeueTo": dequeue_to, "DequeueStatusCallbackUrl": dequeue_status_callback_url, "CallFrom": call_from, @@ -1015,17 +1177,929 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, ) - - return ReservationInstance( + instance = ReservationInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], task_sid=self._solution["task_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -1045,6 +2119,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -1149,6 +2224,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -1172,6 +2311,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1204,6 +2344,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1214,6 +2355,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -1251,7 +2454,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1290,7 +2493,89 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ReservationPage, status code, and headers + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ReservationPage, status code, and headers + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ReservationPage: """ @@ -1302,7 +2587,7 @@ def get_page(self, target_url: str) -> ReservationPage: :returns: Page of ReservationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ReservationPage: """ @@ -1314,7 +2599,7 @@ async def get_page_async(self, target_url: str) -> ReservationPage: :returns: Page of ReservationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ReservationContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/task_channel.py b/twilio/rest/taskrouter/v1/workspace/task_channel.py index 3a4b0a6b9e..ea27998d19 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskChannelContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TaskChannelInstance": """ Fetch the TaskChannelInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "TaskChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -156,6 +194,42 @@ async def update_async( channel_optimized_routing=channel_optimized_routing, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -187,6 +261,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TaskChannelInstance @@ -194,10 +282,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskChannelInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -206,27 +316,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TaskChannelInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TaskChannelInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TaskChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskChannelInstance: + """ + Fetch the TaskChannelInstance + + :returns: The fetched TaskChannelInstance + """ + payload, _, _ = self._fetch() return TaskChannelInstance( self._version, payload, @@ -234,22 +360,46 @@ def fetch(self) -> TaskChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TaskChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskChannelInstance + Fetch the TaskChannelInstance and return response metadata - :returns: The fetched TaskChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TaskChannelInstance: + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + payload, _, _ = await self._fetch_async() return TaskChannelInstance( self._version, payload, @@ -257,18 +407,32 @@ async def fetch_async(self) -> TaskChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> tuple: """ - Update the TaskChannelInstance - - :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. - :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + Internal helper for update operation - :returns: The updated TaskChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -285,10 +449,27 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, @@ -296,18 +477,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TaskChannelInstance + Update the TaskChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - :returns: The updated TaskChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -324,10 +528,27 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, @@ -335,6 +556,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -353,6 +599,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: :param payload: Payload response from the API """ + return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -384,20 +631,17 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) - def create( + def _create( self, friendly_name: str, unique_name: str, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> tuple: """ - Create the TaskChannelInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. - :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - - :returns: The created TaskChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,28 +659,70 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, unique_name: str, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskChannelInstance + Create the TaskChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - :returns: The created TaskChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -454,14 +740,59 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronously create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -512,6 +843,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TaskChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TaskChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -531,6 +912,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -557,6 +939,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -565,6 +948,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TaskChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TaskChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -596,7 +1029,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskChannelPage(self._version, response, self._solution) + return TaskChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -629,7 +1062,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskChannelPage(self._version, response, self._solution) + return TaskChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TaskChannelPage: """ @@ -641,7 +1144,7 @@ def get_page(self, target_url: str) -> TaskChannelPage: :returns: Page of TaskChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TaskChannelPage(self._version, response, self._solution) + return TaskChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TaskChannelPage: """ @@ -653,7 +1156,7 @@ async def get_page_async(self, target_url: str) -> TaskChannelPage: :returns: Page of TaskChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskChannelPage(self._version, response, self._solution) + return TaskChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TaskChannelContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py index 4511a55310..02213bbcc8 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -106,6 +107,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskQueueContext] = None @property @@ -142,6 +144,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TaskQueueInstance": """ Fetch the TaskQueueInstance @@ -160,6 +180,24 @@ async def fetch_async(self) -> "TaskQueueInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -220,6 +258,66 @@ async def update_async( task_order=task_order, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskQueueInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskQueueInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + @property def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: """ @@ -276,6 +374,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._real_time_statistics: Optional[TaskQueueRealTimeStatisticsList] = None self._statistics: Optional[TaskQueueStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TaskQueueInstance @@ -283,10 +395,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskQueueInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -295,27 +429,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskQueueInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TaskQueueInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TaskQueueInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TaskQueueInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskQueueInstance: + """ + Fetch the TaskQueueInstance + + :returns: The fetched TaskQueueInstance + """ + payload, _, _ = self._fetch() return TaskQueueInstance( self._version, payload, @@ -323,22 +473,46 @@ def fetch(self) -> TaskQueueInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TaskQueueInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskQueueInstance + Fetch the TaskQueueInstance and return response metadata - :returns: The fetched TaskQueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TaskQueueInstance: + """ + Asynchronous coroutine to fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + payload, _, _ = await self._fetch_async() return TaskQueueInstance( self._version, payload, @@ -346,7 +520,23 @@ async def fetch_async(self) -> TaskQueueInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, target_workers: Union[str, object] = values.unset, @@ -354,18 +544,12 @@ def update( assignment_activity_sid: Union[str, object] = values.unset, max_reserved_workers: Union[int, object] = values.unset, task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, - ) -> TaskQueueInstance: + ) -> tuple: """ - Update the TaskQueueInstance - - :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. - :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. - :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. - :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. - :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. - :param task_order: + Internal helper for update operation - :returns: The updated TaskQueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -384,10 +568,39 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) return TaskQueueInstance( self._version, payload, @@ -395,7 +608,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, target_workers: Union[str, object] = values.unset, @@ -403,9 +616,9 @@ async def update_async( assignment_activity_sid: Union[str, object] = values.unset, max_reserved_workers: Union[int, object] = values.unset, task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, - ) -> TaskQueueInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TaskQueueInstance + Update the TaskQueueInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. @@ -414,7 +627,38 @@ async def update_async( :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. :param task_order: - :returns: The updated TaskQueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -433,10 +677,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) return TaskQueueInstance( self._version, payload, @@ -444,26 +717,63 @@ async def update_async( sid=self._solution["sid"], ) - @property - def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: - """ - Access the cumulative_statistics + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: """ - if self._cumulative_statistics is None: - self._cumulative_statistics = TaskQueueCumulativeStatisticsList( - self._version, - self._solution["workspace_sid"], - self._solution["sid"], - ) - return self._cumulative_statistics + Asynchronous coroutine to update the TaskQueueInstance and return response metadata - @property - def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: - """ - Access the real_time_statistics - """ - if self._real_time_statistics is None: - self._real_time_statistics = TaskQueueRealTimeStatisticsList( + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = TaskQueueRealTimeStatisticsList( self._version, self._solution["workspace_sid"], self._solution["sid"], @@ -501,6 +811,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: :param payload: Payload response from the API """ + return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -537,7 +848,7 @@ def __init__(self, version: Version, workspace_sid: str): ] = None self._statistics: Optional[TaskQueuesStatisticsList] = None - def create( + def _create( self, friendly_name: str, target_workers: Union[str, object] = values.unset, @@ -545,18 +856,12 @@ def create( task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, reservation_activity_sid: Union[str, object] = values.unset, assignment_activity_sid: Union[str, object] = values.unset, - ) -> TaskQueueInstance: + ) -> tuple: """ - Create the TaskQueueInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. - :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). - :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. - :param task_order: - :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. - :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. - - :returns: The created TaskQueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -575,15 +880,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, target_workers: Union[str, object] = values.unset, @@ -591,9 +925,9 @@ async def create_async( task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, reservation_activity_sid: Union[str, object] = values.unset, assignment_activity_sid: Union[str, object] = values.unset, - ) -> TaskQueueInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskQueueInstance + Create the TaskQueueInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). @@ -602,7 +936,35 @@ async def create_async( :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. - :returns: The created TaskQueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -621,14 +983,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronously create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -707,6 +1132,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TaskQueueInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TaskQueueInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -734,6 +1235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -772,6 +1274,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -784,6 +1287,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TaskQueueInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TaskQueueInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -827,7 +1404,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskQueuePage(self._version, response, self._solution) + return TaskQueuePage(self._version, response, solution=self._solution) async def page_async( self, @@ -872,7 +1449,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskQueuePage(self._version, response, self._solution) + return TaskQueuePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskQueuePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskQueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskQueuePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskQueuePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TaskQueuePage: """ @@ -884,7 +1555,7 @@ def get_page(self, target_url: str) -> TaskQueuePage: :returns: Page of TaskQueueInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TaskQueuePage(self._version, response, self._solution) + return TaskQueuePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> TaskQueuePage: """ @@ -896,7 +1567,7 @@ async def get_page_async(self, target_url: str) -> TaskQueuePage: :returns: Page of TaskQueueInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskQueuePage(self._version, response, self._solution) + return TaskQueuePage(self._version, response, solution=self._solution) @property def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py index 90400c7930..5273d75dea 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,15 +81,12 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def create( - self, body: Union[object, object] = values.unset - ) -> TaskQueueBulkRealTimeStatisticsInstance: + def _create(self, body: Union[object, object] = values.unset) -> tuple: """ - Create the TaskQueueBulkRealTimeStatisticsInstance - - :param body: + Internal helper for create operation - :returns: The created TaskQueueBulkRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -98,23 +96,47 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + payload, _, _ = self._create(body=body) return TaskQueueBulkRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, body: Union[object, object] = values.unset - ) -> TaskQueueBulkRealTimeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance + Create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata :param body: - :returns: The created TaskQueueBulkRealTimeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = body.to_dict() @@ -124,14 +146,41 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + payload, _, _ = await self._create_async(body=body) return TaskQueueBulkRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py index ef851c755a..5741772450 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -119,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None @property @@ -191,6 +193,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TaskQueueCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,27 +280,22 @@ def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the TaskQueueCumulativeStatisticsInstance - - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + Internal helper for fetch operation - :returns: The fetched TaskQueueCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -258,10 +309,36 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return TaskQueueCumulativeStatisticsInstance( self._version, payload, @@ -269,16 +346,16 @@ def fetch( task_queue_sid=self._solution["task_queue_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueCumulativeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + Fetch the TaskQueueCumulativeStatisticsInstance and return response metadata :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. @@ -286,10 +363,39 @@ async def fetch_async( :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. - :returns: The fetched TaskQueueCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -303,10 +409,36 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return TaskQueueCumulativeStatisticsInstance( self._version, payload, @@ -314,6 +446,40 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance and return response metadata + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py index c4eb30ddc0..94dc68cbbc 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None @property @@ -132,6 +134,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the TaskQueueRealTimeStatisticsInstance with HTTP info + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance with HTTP info + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,18 +195,15 @@ def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): **self._solution ) - def fetch( - self, task_channel: Union[str, object] = values.unset - ) -> TaskQueueRealTimeStatisticsInstance: + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: """ - Fetch the TaskQueueRealTimeStatisticsInstance + Internal helper for fetch operation - :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched TaskQueueRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TaskChannel": task_channel, } @@ -186,10 +213,21 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + payload, _, _ = self._fetch(task_channel=task_channel) return TaskQueueRealTimeStatisticsInstance( self._version, payload, @@ -197,18 +235,36 @@ def fetch( task_queue_sid=self._solution["task_queue_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, task_channel: Union[str, object] = values.unset - ) -> TaskQueueRealTimeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + Fetch the TaskQueueRealTimeStatisticsInstance and return response metadata :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched TaskQueueRealTimeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } @@ -218,10 +274,21 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + payload, _, _ = await self._fetch_async(task_channel=task_channel) return TaskQueueRealTimeStatisticsInstance( self._version, payload, @@ -229,6 +296,27 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance and return response metadata + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py index 2d5d631069..444f3925a7 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueStatisticsContext] = None @property @@ -123,6 +125,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TaskQueueStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,27 +212,22 @@ def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): ) ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueStatisticsInstance: + ) -> tuple: """ - Fetch the TaskQueueStatisticsInstance - - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + Internal helper for fetch operation - :returns: The fetched TaskQueueStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -190,10 +241,36 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return TaskQueueStatisticsInstance( self._version, payload, @@ -201,16 +278,16 @@ def fetch( task_queue_sid=self._solution["task_queue_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + Fetch the TaskQueueStatisticsInstance and return response metadata :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. @@ -218,10 +295,39 @@ async def fetch_async( :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. - :returns: The fetched TaskQueueStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -235,10 +341,36 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return TaskQueueStatisticsInstance( self._version, payload, @@ -246,6 +378,40 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance and return response metadata + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py index 036f6ad92b..aa6fb95b0f 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskQueuesStatisticsInstance: :param payload: Payload response from the API """ + return TaskQueuesStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -185,6 +187,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end_date: Union[datetime, object] = values.unset, @@ -216,6 +306,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_date=end_date, @@ -260,6 +351,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -274,6 +366,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end_date: Union[datetime, object] = values.unset, @@ -323,7 +501,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -374,7 +554,119 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskQueuesStatisticsPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TaskQueuesStatisticsPage, status code, and headers + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: """ @@ -386,7 +678,9 @@ def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: :returns: Page of TaskQueuesStatisticsInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: """ @@ -398,7 +692,9 @@ async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: :returns: Page of TaskQueuesStatisticsInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + return TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py index 38aede84bb..1295d3716e 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerContext] = None @property @@ -128,6 +130,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "WorkerInstance": """ Fetch the WorkerInstance @@ -146,6 +176,24 @@ async def fetch_async(self) -> "WorkerInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -200,6 +248,60 @@ async def update_async( reject_pending_reservations=reject_pending_reservations, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + @property def reservations(self) -> ReservationList: """ @@ -254,13 +356,12 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._worker_channels: Optional[WorkerChannelList] = None self._statistics: Optional[WorkerStatisticsList] = None - def delete(self, if_match: Union[str, object] = values.unset) -> bool: + def _delete(self, if_match: Union[str, object] = values.unset) -> tuple: """ - Deletes the WorkerInstance - - :param if_match: The If-Match HTTP request header + Internal helper for delete operation - :returns: True if delete succeeds, False otherwise + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of( { @@ -270,16 +371,41 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ - Asynchronous coroutine that deletes the WorkerInstance + Deletes the WorkerInstance :param if_match: The If-Match HTTP request header :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(if_match=if_match) + return success + + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the WorkerInstance and return response metadata + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self, if_match: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "If-Match": if_match, @@ -288,24 +414,58 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo headers = values.of({}) - return await self._version.delete_async( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers ) - def fetch(self) -> WorkerInstance: + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: """ - Fetch the WorkerInstance + Asynchronous coroutine that deletes the WorkerInstance + :param if_match: The If-Match HTTP request header - :returns: The fetched WorkerInstance + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async(if_match=if_match) + return success + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkerInstance and return response metadata + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async(if_match=if_match) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkerInstance: + """ + Fetch the WorkerInstance + + :returns: The fetched WorkerInstance + """ + payload, _, _ = self._fetch() return WorkerInstance( self._version, payload, @@ -313,22 +473,46 @@ def fetch(self) -> WorkerInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WorkerInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkerInstance + Fetch the WorkerInstance and return response metadata - :returns: The fetched WorkerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WorkerInstance: + """ + Asynchronous coroutine to fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + payload, _, _ = await self._fetch_async() return WorkerInstance( self._version, payload, @@ -336,24 +520,35 @@ async def fetch_async(self) -> WorkerInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, if_match: Union[str, object] = values.unset, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, reject_pending_reservations: Union[bool, object] = values.unset, - ) -> WorkerInstance: + ) -> tuple: """ - Update the WorkerInstance - - :param if_match: The If-Match HTTP request header - :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. - :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. - :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. - :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + Internal helper for update operation - :returns: The updated WorkerInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -377,10 +572,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + payload, _, _ = self._update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) return WorkerInstance( self._version, payload, @@ -388,16 +609,16 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, reject_pending_reservations: Union[bool, object] = values.unset, - ) -> WorkerInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WorkerInstance + Update the WorkerInstance and return response metadata :param if_match: The If-Match HTTP request header :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. @@ -405,7 +626,36 @@ async def update_async( :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. - :returns: The updated WorkerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -429,10 +679,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronous coroutine to update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) return WorkerInstance( self._version, payload, @@ -440,26 +716,60 @@ async def update_async( sid=self._solution["sid"], ) - @property - def reservations(self) -> ReservationList: - """ - Access the reservations + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - if self._reservations is None: - self._reservations = ReservationList( - self._version, - self._solution["workspace_sid"], - self._solution["sid"], - ) - return self._reservations + Asynchronous coroutine to update the WorkerInstance and return response metadata - @property - def worker_channels(self) -> WorkerChannelList: - """ - Access the worker_channels - """ - if self._worker_channels is None: - self._worker_channels = WorkerChannelList( + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + instance = WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations + + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + if self._worker_channels is None: + self._worker_channels = WorkerChannelList( self._version, self._solution["workspace_sid"], self._solution["sid"], @@ -497,6 +807,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: :param payload: Payload response from the API """ + return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -532,20 +843,17 @@ def __init__(self, version: Version, workspace_sid: str): self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None self._statistics: Optional[WorkersStatisticsList] = None - def create( + def _create( self, friendly_name: str, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> WorkerInstance: + ) -> tuple: """ - Create the WorkerInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. - :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. - :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. - - :returns: The created WorkerInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -561,28 +869,70 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> WorkerInstance: + ) -> ApiResponse: """ - Asynchronously create the WorkerInstance + Create the WorkerInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. - :returns: The created WorkerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -598,14 +948,59 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronously create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkerInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, activity_name: Union[str, object] = values.unset, @@ -708,6 +1103,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WorkerInstance and returns headers from first page + + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WorkerInstance and returns headers from first page + + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, activity_name: Union[str, object] = values.unset, @@ -743,6 +1238,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( activity_name=activity_name, @@ -793,6 +1289,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -809,6 +1306,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WorkerInstance and returns headers from first page + + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WorkerInstance and returns headers from first page + + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, activity_name: Union[str, object] = values.unset, @@ -864,7 +1459,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkerPage(self._version, response, self._solution) + return WorkerPage(self._version, response, solution=self._solution) async def page_async( self, @@ -921,7 +1516,125 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkerPage(self._version, response, self._solution) + return WorkerPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkerPage, status code, and headers + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkerPage, status code, and headers + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkerPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WorkerPage: """ @@ -933,7 +1646,7 @@ def get_page(self, target_url: str) -> WorkerPage: :returns: Page of WorkerInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WorkerPage(self._version, response, self._solution) + return WorkerPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WorkerPage: """ @@ -945,7 +1658,7 @@ async def get_page_async(self, target_url: str) -> WorkerPage: :returns: Page of WorkerInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WorkerPage(self._version, response, self._solution) + return WorkerPage(self._version, response, solution=self._solution) @property def cumulative_statistics(self) -> WorkersCumulativeStatisticsList: diff --git a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py index 11d1ea610d..227b2b83d7 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -96,6 +97,7 @@ def __init__( "worker_sid": worker_sid, "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None @property @@ -133,6 +135,24 @@ async def fetch_async(self) -> "ReservationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -241,7 +261,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -416,7 +436,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -483,86 +503,7 @@ async def update_async( jitter_buffer_size=jitter_buffer_size, ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) - - -class ReservationContext(InstanceContext): - - def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): - """ - Initialize the ReservationContext - - :param version: Version that contains the resource - :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to update. - :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to update. - :param sid: The SID of the WorkerReservation resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "workspace_sid": workspace_sid, - "worker_sid": worker_sid, - "sid": sid, - } - self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}".format( - **self._solution - ) - - def fetch(self) -> ReservationInstance: - """ - Fetch the ReservationInstance - - - :returns: The fetched ReservationInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - worker_sid=self._solution["worker_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ReservationInstance: - """ - Asynchronous coroutine to fetch the ReservationInstance - - - :returns: The fetched ReservationInstance - """ - - headers = values.of({}) - - headers["Accept"] = "application/json" - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers - ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - worker_sid=self._solution["worker_sid"], - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, if_match: Union[str, object] = values.unset, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -621,9 +562,9 @@ def update( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -670,7 +611,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -679,103 +620,65 @@ def update( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "CallUrl": call_url, - "CallStatusCallbackUrl": call_status_callback_url, - "CallAccept": serialize.boolean_to_string(call_accept), - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": serialize.boolean_to_string(redirect_accept), - "RedirectUrl": redirect_url, - "To": to, - "From": from_, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "Timeout": timeout, - "Record": serialize.boolean_to_string(record), - "Muted": serialize.boolean_to_string(muted), - "Beep": beep, - "StartConferenceOnEnter": serialize.boolean_to_string( - start_conference_on_enter - ), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": serialize.boolean_to_string(early_media), - "MaxParticipants": max_participants, - "ConferenceStatusCallback": conference_status_callback, - "ConferenceStatusCallbackMethod": conference_status_callback_method, - "ConferenceStatusCallbackEvent": serialize.map( - conference_status_callback_event, lambda e: e - ), - "ConferenceRecord": conference_record, - "ConferenceTrim": conference_trim, - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "ConferenceRecordingStatusCallback": conference_recording_status_callback, - "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, - "Region": region, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "DequeueStatusCallbackEvent": serialize.map( - dequeue_status_callback_event, lambda e: e - ), - "PostWorkActivitySid": post_work_activity_sid, - "EndConferenceOnCustomerExit": serialize.boolean_to_string( - end_conference_on_customer_exit - ), - "BeepOnCustomerEntrance": serialize.boolean_to_string( - beep_on_customer_entrance - ), - "JitterBufferSize": jitter_buffer_size, - } - ) - headers = values.of({}) - - if not ( - if_match is values.unset or (isinstance(if_match, str) and not if_match) - ): - headers["If-Match"] = if_match - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ReservationInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - worker_sid=self._solution["worker_sid"], - sid=self._solution["sid"], + return self._proxy.update_with_http_info( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, ) - async def update_async( + async def update_with_http_info_async( self, if_match: Union[str, object] = values.unset, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -834,9 +737,9 @@ async def update_async( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ReservationInstance + Asynchronous coroutine to update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -883,7 +786,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -892,24 +795,794 @@ async def update_async( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, + return await self._proxy.update_with_http_info_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to update. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to update. + :param sid: The SID of the WorkerReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = self._fetch() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + payload, _, _ = await self._fetch_async() + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, "CallUrl": call_url, "CallStatusCallbackUrl": call_status_callback_url, "CallAccept": serialize.boolean_to_string(call_accept), @@ -974,19 +1647,376 @@ async def update_async( headers["Content-Type"] = "application/x-www-form-urlencoded" - headers["Accept"] = "application/json" + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, ) - - return ReservationInstance( + instance = ReservationInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], worker_sid=self._solution["worker_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -1006,6 +2036,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -1104,6 +2135,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -1125,6 +2212,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1154,6 +2242,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1163,6 +2252,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ReservationInstance and returns headers from first page + + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, reservation_status: Union["ReservationInstance.Status", object] = values.unset, @@ -1197,7 +2342,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1233,7 +2378,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ReservationPage, status code, and headers + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ReservationPage, status code, and headers + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ReservationPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ReservationPage: """ @@ -1245,7 +2466,7 @@ def get_page(self, target_url: str) -> ReservationPage: :returns: Page of ReservationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ReservationPage: """ @@ -1257,7 +2478,7 @@ async def get_page_async(self, target_url: str) -> ReservationPage: :returns: Page of ReservationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ReservationPage(self._version, response, self._solution) + return ReservationPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ReservationContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py index 6e3cc9c1dd..61d407fd38 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,7 @@ def __init__( "worker_sid": worker_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerChannelContext] = None @property @@ -117,6 +119,24 @@ async def fetch_async(self) -> "WorkerChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, capacity: Union[int, object] = values.unset, @@ -153,6 +173,42 @@ async def update_async( available=available, ) + def update_with_http_info( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkerChannelInstance with HTTP info + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + capacity=capacity, + available=available, + ) + + async def update_with_http_info_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerChannelInstance with HTTP info + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + capacity=capacity, + available=available, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -188,20 +244,30 @@ def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: s ) ) - def fetch(self) -> WorkerChannelInstance: + def _fetch(self) -> tuple: """ - Fetch the WorkerChannelInstance - + Internal helper for fetch operation - :returns: The fetched WorkerChannelInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> WorkerChannelInstance: + """ + Fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + payload, _, _ = self._fetch() return WorkerChannelInstance( self._version, payload, @@ -210,22 +276,47 @@ def fetch(self) -> WorkerChannelInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WorkerChannelInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkerChannelInstance + Fetch the WorkerChannelInstance and return response metadata - :returns: The fetched WorkerChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WorkerChannelInstance: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + payload, _, _ = await self._fetch_async() return WorkerChannelInstance( self._version, payload, @@ -234,18 +325,33 @@ async def fetch_async(self) -> WorkerChannelInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, capacity: Union[int, object] = values.unset, available: Union[bool, object] = values.unset, - ) -> WorkerChannelInstance: + ) -> tuple: """ - Update the WorkerChannelInstance - - :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. - :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + Internal helper for update operation - :returns: The updated WorkerChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -260,10 +366,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + payload, _, _ = self._update(capacity=capacity, available=available) return WorkerChannelInstance( self._version, payload, @@ -272,18 +392,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, capacity: Union[int, object] = values.unset, available: Union[bool, object] = values.unset, - ) -> WorkerChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WorkerChannelInstance + Update the WorkerChannelInstance and return response metadata :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. - :returns: The updated WorkerChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + capacity=capacity, available=available + ) + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +441,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + payload, _, _ = await self._update_async(capacity=capacity, available=available) return WorkerChannelInstance( self._version, payload, @@ -310,6 +467,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerChannelInstance and return response metadata + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + capacity=capacity, available=available + ) + instance = WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -328,6 +510,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: :param payload: Payload response from the API """ + return WorkerChannelInstance( self._version, payload, @@ -416,6 +599,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WorkerChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WorkerChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -435,6 +668,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -461,6 +695,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -469,6 +704,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WorkerChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WorkerChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -500,7 +785,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkerChannelPage(self._version, response, self._solution) + return WorkerChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -533,7 +818,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkerChannelPage(self._version, response, self._solution) + return WorkerChannelPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkerChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkerChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkerChannelPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkerChannelPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WorkerChannelPage: """ @@ -545,7 +900,7 @@ def get_page(self, target_url: str) -> WorkerChannelPage: :returns: Page of WorkerChannelInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WorkerChannelPage(self._version, response, self._solution) + return WorkerChannelPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WorkerChannelPage: """ @@ -557,7 +912,7 @@ async def get_page_async(self, target_url: str) -> WorkerChannelPage: :returns: Page of WorkerChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WorkerChannelPage(self._version, response, self._solution) + return WorkerChannelPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WorkerChannelContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py index eea670aa7d..f2fbcd5c34 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__( "workspace_sid": workspace_sid, "worker_sid": worker_sid, } + self._context: Optional[WorkerStatisticsContext] = None @property @@ -115,6 +117,54 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkerStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,25 +198,21 @@ def __init__(self, version: Version, workspace_sid: str, worker_sid: str): ) ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkerStatisticsInstance: + ) -> tuple: """ - Fetch the WorkerStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + Internal helper for fetch operation - :returns: The fetched WorkerStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -179,10 +225,33 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) return WorkerStatisticsInstance( self._version, payload, @@ -190,25 +259,52 @@ def fetch( worker_sid=self._solution["worker_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkerStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkerStatisticsInstance + Fetch the WorkerStatisticsInstance and return response metadata :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkerStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + instance = WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -221,10 +317,33 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) return WorkerStatisticsInstance( self._version, payload, @@ -232,6 +351,37 @@ async def fetch_async( worker_sid=self._solution["worker_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + instance = WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py index 48a78710e2..dbcce53c8c 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersCumulativeStatisticsContext] = None @property @@ -139,6 +141,54 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkersCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,25 +220,21 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkersCumulativeStatisticsInstance + Internal helper for fetch operation - :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkersCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -201,35 +247,84 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersCumulativeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + Fetch the WorkersCumulativeStatisticsInstance and return response metadata :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkersCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + instance = WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -242,16 +337,69 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) return WorkersCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance and return response metadata + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + instance = WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py index 2e9970478e..9efc95193a 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersRealTimeStatisticsContext] = None @property @@ -90,6 +92,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkersRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -121,18 +151,15 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( - self, task_channel: Union[str, object] = values.unset - ) -> WorkersRealTimeStatisticsInstance: + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: """ - Fetch the WorkersRealTimeStatisticsInstance + Internal helper for fetch operation - :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkersRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TaskChannel": task_channel, } @@ -142,28 +169,56 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + payload, _, _ = self._fetch(task_channel=task_channel) return WorkersRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, task_channel: Union[str, object] = values.unset - ) -> WorkersRealTimeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + Fetch the WorkersRealTimeStatisticsInstance and return response metadata :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkersRealTimeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } @@ -173,16 +228,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + payload, _, _ = await self._fetch_async(task_channel=task_channel) return WorkersRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance and return response metadata + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py index 31c79ee6ba..8a3a21b6bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersStatisticsContext] = None @property @@ -125,6 +127,72 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkersStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,7 +222,7 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, @@ -163,22 +231,15 @@ def fetch( task_queue_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersStatisticsInstance: + ) -> tuple: """ - Fetch the WorkersStatisticsInstance + Internal helper for fetch operation - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. - :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. - :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkersStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -194,17 +255,49 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) return WorkersStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, @@ -213,9 +306,9 @@ async def fetch_async( task_queue_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkersStatisticsInstance + Fetch the WorkersStatisticsInstance and return response metadata :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -225,10 +318,42 @@ async def fetch_async( :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkersStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + instance = WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -244,16 +369,87 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) return WorkersStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + instance = WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py index 619ae1bce9..547db90579 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkflowContext] = None @property @@ -121,6 +123,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkflowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WorkflowInstance": """ Fetch the WorkflowInstance @@ -139,6 +159,24 @@ async def fetch_async(self) -> "WorkflowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkflowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -199,6 +237,66 @@ async def update_async( re_evaluate_tasks=re_evaluate_tasks, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkflowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkflowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + @property def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ @@ -255,6 +353,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None self._statistics: Optional[WorkflowStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WorkflowInstance @@ -262,10 +374,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkflowInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -274,27 +408,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WorkflowInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WorkflowInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WorkflowInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkflowInstance: + """ + Fetch the WorkflowInstance + + :returns: The fetched WorkflowInstance + """ + payload, _, _ = self._fetch() return WorkflowInstance( self._version, payload, @@ -302,22 +452,46 @@ def fetch(self) -> WorkflowInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WorkflowInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkflowInstance + Fetch the WorkflowInstance and return response metadata - :returns: The fetched WorkflowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WorkflowInstance: + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + payload, _, _ = await self._fetch_async() return WorkflowInstance( self._version, payload, @@ -325,7 +499,23 @@ async def fetch_async(self) -> WorkflowInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, assignment_callback_url: Union[str, object] = values.unset, @@ -333,18 +523,12 @@ def update( configuration: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, re_evaluate_tasks: Union[str, object] = values.unset, - ) -> WorkflowInstance: + ) -> tuple: """ - Update the WorkflowInstance - - :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. - :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. - :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. - :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. - :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. - :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + Internal helper for update operation - :returns: The updated WorkflowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,10 +547,39 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) return WorkflowInstance( self._version, payload, @@ -374,7 +587,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, assignment_callback_url: Union[str, object] = values.unset, @@ -382,9 +595,9 @@ async def update_async( configuration: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, re_evaluate_tasks: Union[str, object] = values.unset, - ) -> WorkflowInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the WorkflowInstance + Update the WorkflowInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. @@ -393,7 +606,38 @@ async def update_async( :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. - :returns: The updated WorkflowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -412,10 +656,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) return WorkflowInstance( self._version, payload, @@ -423,6 +696,43 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkflowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + instance = WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ @@ -480,6 +790,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: :param payload: Payload response from the API """ + return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -511,24 +822,19 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) - def create( + def _create( self, friendly_name: str, configuration: str, assignment_callback_url: Union[str, object] = values.unset, fallback_assignment_callback_url: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, - ) -> WorkflowInstance: + ) -> tuple: """ - Create the WorkflowInstance - - :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. - :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. - :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. - :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. - :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + Internal helper for create operation - :returns: The created WorkflowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -546,24 +852,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, configuration: str, assignment_callback_url: Union[str, object] = values.unset, fallback_assignment_callback_url: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, - ) -> WorkflowInstance: + ) -> ApiResponse: """ - Asynchronously create the WorkflowInstance + Create the WorkflowInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. @@ -571,7 +903,33 @@ async def create_async( :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. - :returns: The created WorkflowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -589,14 +947,71 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronously create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkflowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -653,6 +1068,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WorkflowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WorkflowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -674,6 +1145,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -703,6 +1175,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -712,6 +1185,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WorkflowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WorkflowInstance and returns headers from first page + + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -746,7 +1275,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkflowPage(self._version, response, self._solution) + return WorkflowPage(self._version, response, solution=self._solution) async def page_async( self, @@ -782,7 +1311,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WorkflowPage(self._version, response, self._solution) + return WorkflowPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkflowPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WorkflowPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WorkflowPage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WorkflowPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WorkflowPage: """ @@ -794,7 +1399,7 @@ def get_page(self, target_url: str) -> WorkflowPage: :returns: Page of WorkflowInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WorkflowPage(self._version, response, self._solution) + return WorkflowPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WorkflowPage: """ @@ -806,7 +1411,7 @@ async def get_page_async(self, target_url: str) -> WorkflowPage: :returns: Page of WorkflowInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WorkflowPage(self._version, response, self._solution) + return WorkflowPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WorkflowContext: """ diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py index d6d7c094cc..f104fd41bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -119,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None @property @@ -191,6 +193,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkflowCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,27 +280,22 @@ def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkflowCumulativeStatisticsInstance - - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + Internal helper for fetch operation - :returns: The fetched WorkflowCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -258,10 +309,36 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkflowCumulativeStatisticsInstance( self._version, payload, @@ -269,16 +346,16 @@ def fetch( workflow_sid=self._solution["workflow_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowCumulativeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + Fetch the WorkflowCumulativeStatisticsInstance and return response metadata :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. @@ -286,10 +363,39 @@ async def fetch_async( :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. - :returns: The fetched WorkflowCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -303,10 +409,36 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkflowCumulativeStatisticsInstance( self._version, payload, @@ -314,6 +446,40 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance and return response metadata + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py index 9387622518..944dac550d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None @property @@ -112,6 +114,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkflowRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,18 +175,15 @@ def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): **self._solution ) - def fetch( - self, task_channel: Union[str, object] = values.unset - ) -> WorkflowRealTimeStatisticsInstance: + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: """ - Fetch the WorkflowRealTimeStatisticsInstance + Internal helper for fetch operation - :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkflowRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TaskChannel": task_channel, } @@ -166,10 +193,21 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + payload, _, _ = self._fetch(task_channel=task_channel) return WorkflowRealTimeStatisticsInstance( self._version, payload, @@ -177,18 +215,36 @@ def fetch( workflow_sid=self._solution["workflow_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, task_channel: Union[str, object] = values.unset - ) -> WorkflowRealTimeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + Fetch the WorkflowRealTimeStatisticsInstance and return response metadata :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkflowRealTimeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } @@ -198,10 +254,21 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + payload, _, _ = await self._fetch_async(task_channel=task_channel) return WorkflowRealTimeStatisticsInstance( self._version, payload, @@ -209,6 +276,27 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance and return response metadata + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py index e49bd32d6e..1aa812c61d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowStatisticsContext] = None @property @@ -123,6 +125,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkflowStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,27 +212,22 @@ def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): ) ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowStatisticsInstance: + ) -> tuple: """ - Fetch the WorkflowStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + Internal helper for fetch operation - :returns: The fetched WorkflowStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -190,10 +241,36 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkflowStatisticsInstance( self._version, payload, @@ -201,16 +278,16 @@ def fetch( workflow_sid=self._solution["workflow_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkflowStatisticsInstance + Fetch the WorkflowStatisticsInstance and return response metadata :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -218,10 +295,39 @@ async def fetch_async( :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. - :returns: The fetched WorkflowStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -235,10 +341,36 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkflowStatisticsInstance( self._version, payload, @@ -246,6 +378,40 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py index 3747b395d2..8d7262cdb0 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -110,6 +111,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None @property @@ -181,6 +183,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkspaceCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -212,27 +268,22 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkspaceCumulativeStatisticsInstance - - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + Internal helper for fetch operation - :returns: The fetched WorkspaceCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -246,26 +297,52 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + payload, _, _ = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceCumulativeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + Fetch the WorkspaceCumulativeStatisticsInstance and return response metadata :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. @@ -273,10 +350,38 @@ async def fetch_async( :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. - :returns: The fetched WorkspaceCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -290,16 +395,75 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceCumulativeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance and return response metadata + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py index 923a94bf3a..559ec20f14 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None @property @@ -110,6 +112,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkspaceRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,18 +171,15 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( - self, task_channel: Union[str, object] = values.unset - ) -> WorkspaceRealTimeStatisticsInstance: + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: """ - Fetch the WorkspaceRealTimeStatisticsInstance + Internal helper for fetch operation - :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkspaceRealTimeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TaskChannel": task_channel, } @@ -162,28 +189,56 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + payload, _, _ = self._fetch(task_channel=task_channel) return WorkspaceRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, task_channel: Union[str, object] = values.unset - ) -> WorkspaceRealTimeStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + Fetch the WorkspaceRealTimeStatisticsInstance and return response metadata :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :returns: The fetched WorkspaceRealTimeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(task_channel=task_channel) + instance = WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } @@ -193,16 +248,47 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + payload, _, _ = await self._fetch_async(task_channel=task_channel) return WorkspaceRealTimeStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance and return response metadata + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py index b8414a5c6c..e30fecf3e1 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceStatisticsContext] = None @property @@ -113,6 +115,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkspaceStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -140,27 +196,22 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Statistics".format(**self._solution) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceStatisticsInstance: + ) -> tuple: """ - Fetch the WorkspaceStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + Internal helper for fetch operation - :returns: The fetched WorkspaceStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -174,26 +225,52 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + payload, _, _ = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceStatisticsInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + Fetch the WorkspaceStatisticsInstance and return response metadata :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -201,10 +278,38 @@ async def fetch_async( :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. - :returns: The fetched WorkspaceStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -218,16 +323,75 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + payload, _, _ = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) return WorkspaceStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/trunking/v1/trunk/__init__.py b/twilio/rest/trunking/v1/trunk/__init__.py index 6a93a83233..7697c323b6 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ class TransferSetting(object): :ivar transfer_caller_id: :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. :ivar auth_type: The types of authentication mapped to the domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If both are mapped, the values are returned in a comma delimited list. If empty, the domain will not receive any traffic. + :ivar symmetric_rtp_enabled: Whether Symmetric RTP is enabled for the trunk. When Symmetric RTP is disabled, Twilio will send RTP to the destination negotiated in the SDP. Disabling Symmetric RTP is considered to be more secure and therefore recommended. See [Symmetric RTP](https://www.twilio.com/docs/sip-trunking#symmetric-rtp) for more information. :ivar auth_type_set: Reserved. :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. @@ -80,6 +82,9 @@ def __init__( ) self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") self.auth_type: Optional[str] = payload.get("auth_type") + self.symmetric_rtp_enabled: Optional[bool] = payload.get( + "symmetric_rtp_enabled" + ) self.auth_type_set: Optional[List[str]] = payload.get("auth_type_set") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -94,6 +99,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[TrunkContext] = None @property @@ -129,6 +135,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrunkInstance": """ Fetch the TrunkInstance @@ -147,6 +171,24 @@ async def fetch_async(self) -> "TrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -223,6 +265,82 @@ async def update_async( transfer_caller_id=transfer_caller_id, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + @property def credentials_lists(self) -> CredentialListList: """ @@ -291,6 +409,20 @@ def __init__(self, version: Version, sid: str): self._phone_numbers: Optional[PhoneNumberList] = None self._recordings: Optional[RecordingList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrunkInstance @@ -298,10 +430,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrunkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -310,56 +464,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TrunkInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TrunkInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + :returns: The fetched TrunkInstance + """ + payload, _, _ = self._fetch() return TrunkInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> TrunkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrunkInstance + Fetch the TrunkInstance and return response metadata - :returns: The fetched TrunkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + payload, _, _ = await self._fetch_async() return TrunkInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -371,20 +579,12 @@ def update( transfer_caller_id: Union[ "TrunkInstance.TransferCallerId", object ] = values.unset, - ) -> TrunkInstance: + ) -> tuple: """ - Update the TrunkInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. - :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. - :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. - :param transfer_mode: - :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param transfer_caller_id: + Internal helper for update operation - :returns: The updated TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -405,13 +605,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TrunkInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -425,7 +623,7 @@ async def update_async( ] = values.unset, ) -> TrunkInstance: """ - Asynchronous coroutine to update the TrunkInstance + Update the TrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. @@ -438,6 +636,77 @@ async def update_async( :returns: The updated TrunkInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -457,25 +726,102 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return TrunkInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def credentials_lists(self) -> CredentialListList: - """ - Access the credentials_lists + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: """ - if self._credentials_lists is None: - self._credentials_lists = CredentialListList( - self._version, - self._solution["sid"], - ) - return self._credentials_lists + Asynchronous coroutine to update the TrunkInstance - @property + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def credentials_lists(self) -> CredentialListList: + """ + Access the credentials_lists + """ + if self._credentials_lists is None: + self._credentials_lists = CredentialListList( + self._version, + self._solution["sid"], + ) + return self._credentials_lists + + @property def ip_access_control_lists(self) -> IpAccessControlListList: """ Access the ip_access_control_lists @@ -541,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: :param payload: Payload response from the API """ + return TrunkInstance(self._version, payload) def __repr__(self) -> str: @@ -565,7 +912,7 @@ def __init__(self, version: Version): self._uri = "/Trunks" - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -577,20 +924,12 @@ def create( transfer_caller_id: Union[ "TrunkInstance.TransferCallerId", object ] = values.unset, - ) -> TrunkInstance: + ) -> tuple: """ - Create the TrunkInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. - :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. - :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. - :param transfer_mode: - :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param transfer_caller_id: - - :returns: The created TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -611,13 +950,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TrunkInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -631,7 +968,7 @@ async def create_async( ] = values.unset, ) -> TrunkInstance: """ - Asynchronously create the TrunkInstance + Create the TrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. @@ -644,6 +981,77 @@ async def create_async( :returns: The created TrunkInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + return TrunkInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -663,12 +1071,89 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronously create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) return TrunkInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -719,6 +1204,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -738,6 +1273,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -764,6 +1300,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -772,6 +1309,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -838,6 +1425,76 @@ async def page_async( ) return TrunkPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TrunkPage: """ Retrieve a specific page of TrunkInstance records from the API. diff --git a/twilio/rest/trunking/v1/trunk/credential_list.py b/twilio/rest/trunking/v1/trunk/credential_list.py index 09ffc99260..540c501396 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListInstance": """ Fetch the CredentialListInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "CredentialListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/CredentialLists/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListInstance @@ -148,10 +200,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -160,27 +234,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CredentialListInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CredentialListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CredentialListInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = self._fetch() return CredentialListInstance( self._version, payload, @@ -188,22 +278,46 @@ def fetch(self) -> CredentialListInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CredentialListInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CredentialListInstance + Fetch the CredentialListInstance and return response metadata - :returns: The fetched CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + payload, _, _ = await self._fetch_async() return CredentialListInstance( self._version, payload, @@ -211,6 +325,22 @@ async def fetch_async(self) -> CredentialListInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -229,6 +359,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -260,13 +391,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) - def create(self, credential_list_sid: str) -> CredentialListInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the CredentialListInstance - - :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + Internal helper for create operation - :returns: The created CredentialListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -280,21 +410,45 @@ def create(self, credential_list_sid: str) -> CredentialListInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, credential_list_sid: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + payload, _, _ = self._create(credential_list_sid=credential_list_sid) return CredentialListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async(self, credential_list_sid: str) -> CredentialListInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the CredentialListInstance + Create the CredentialListInstance and return response metadata :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. - :returns: The created CredentialListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,14 +462,43 @@ async def create_async(self, credential_list_sid: str) -> CredentialListInstance headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, credential_list_sid: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + payload, _, _ = await self._create_async( + credential_list_sid=credential_list_sid + ) return CredentialListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async( + self, credential_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the CredentialListInstance and return response metadata + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credential_list_sid=credential_list_sid + ) + instance = CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -366,6 +549,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -385,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -411,6 +645,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -419,6 +654,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CredentialListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -450,7 +735,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -483,7 +768,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CredentialListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CredentialListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CredentialListPage: """ @@ -495,7 +850,7 @@ def get_page(self, target_url: str) -> CredentialListPage: :returns: Page of CredentialListInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> CredentialListPage: """ @@ -507,7 +862,7 @@ async def get_page_async(self, target_url: str) -> CredentialListPage: :returns: Page of CredentialListInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CredentialListPage(self._version, response, self._solution) + return CredentialListPage(self._version, response, solution=self._solution) def get(self, sid: str) -> CredentialListContext: """ diff --git a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py index ec5a59de69..49c56e5cbc 100644 --- a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py +++ b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListInstance": """ Fetch the IpAccessControlListInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "IpAccessControlListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListInstance @@ -150,10 +202,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -162,27 +236,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IpAccessControlListInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IpAccessControlListInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + :returns: The fetched IpAccessControlListInstance + """ + payload, _, _ = self._fetch() return IpAccessControlListInstance( self._version, payload, @@ -190,22 +280,46 @@ def fetch(self) -> IpAccessControlListInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> IpAccessControlListInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpAccessControlListInstance + Fetch the IpAccessControlListInstance and return response metadata - :returns: The fetched IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + payload, _, _ = await self._fetch_async() return IpAccessControlListInstance( self._version, payload, @@ -213,6 +327,22 @@ async def fetch_async(self) -> IpAccessControlListInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -231,6 +361,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -262,13 +393,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) - def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the IpAccessControlListInstance - - :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + Internal helper for create operation - :returns: The created IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -282,23 +412,47 @@ def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the IpAccessControlListInstance + Create the IpAccessControlListInstance and return response metadata :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. - :returns: The created IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -312,14 +466,45 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListInstance and return response metadata + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -370,6 +555,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -389,6 +624,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -415,6 +651,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -423,6 +660,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpAccessControlListInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -454,7 +741,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -487,7 +774,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IpAccessControlListPage: """ @@ -499,7 +856,7 @@ def get_page(self, target_url: str) -> IpAccessControlListPage: :returns: Page of IpAccessControlListInstance """ response = self._version.domain.twilio.request("GET", target_url) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> IpAccessControlListPage: """ @@ -511,7 +868,7 @@ async def get_page_async(self, target_url: str) -> IpAccessControlListPage: :returns: Page of IpAccessControlListInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return IpAccessControlListPage(self._version, response, self._solution) + return IpAccessControlListPage(self._version, response, solution=self._solution) def get(self, sid: str) -> IpAccessControlListContext: """ diff --git a/twilio/rest/trunking/v1/trunk/origination_url.py b/twilio/rest/trunking/v1/trunk/origination_url.py index 082fa34beb..4ac87498f8 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[OriginationUrlContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "OriginationUrlInstance": """ Fetch the OriginationUrlInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "OriginationUrlInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, weight: Union[int, object] = values.unset, @@ -174,6 +212,60 @@ async def update_async( sip_url=sip_url, ) + def update_with_http_info( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OriginationUrlInstance with HTTP info + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + async def update_with_http_info_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OriginationUrlInstance with HTTP info + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +295,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the OriginationUrlInstance @@ -210,10 +316,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OriginationUrlInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -222,27 +350,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> OriginationUrlInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the OriginationUrlInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched OriginationUrlInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> OriginationUrlInstance: + """ + Fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + payload, _, _ = self._fetch() return OriginationUrlInstance( self._version, payload, @@ -250,22 +394,46 @@ def fetch(self) -> OriginationUrlInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> OriginationUrlInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the OriginationUrlInstance + Fetch the OriginationUrlInstance and return response metadata - :returns: The fetched OriginationUrlInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> OriginationUrlInstance: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + payload, _, _ = await self._fetch_async() return OriginationUrlInstance( self._version, payload, @@ -273,24 +441,35 @@ async def fetch_async(self) -> OriginationUrlInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, weight: Union[int, object] = values.unset, priority: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, friendly_name: Union[str, object] = values.unset, sip_url: Union[str, object] = values.unset, - ) -> OriginationUrlInstance: + ) -> tuple: """ - Update the OriginationUrlInstance + Internal helper for update operation - :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. - :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. - :param enabled: Whether the URL is enabled. The default is `true`. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. - - :returns: The updated OriginationUrlInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +487,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + payload, _, _ = self._update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, @@ -319,16 +524,16 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, weight: Union[int, object] = values.unset, priority: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, friendly_name: Union[str, object] = values.unset, sip_url: Union[str, object] = values.unset, - ) -> OriginationUrlInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the OriginationUrlInstance + Update the OriginationUrlInstance and return response metadata :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. @@ -336,7 +541,36 @@ async def update_async( :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. - :returns: The updated OriginationUrlInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -354,10 +588,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + payload, _, _ = await self._update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, @@ -365,6 +625,40 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OriginationUrlInstance and return response metadata + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -383,6 +677,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: :param payload: Payload response from the API """ + return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -414,24 +709,19 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) - def create( + def _create( self, weight: int, priority: int, enabled: bool, friendly_name: str, sip_url: str, - ) -> OriginationUrlInstance: + ) -> tuple: """ - Create the OriginationUrlInstance - - :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. - :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. - :param enabled: Whether the URL is enabled. The default is `true`. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + Internal helper for create operation - :returns: The created OriginationUrlInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -449,24 +739,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + payload, _, _ = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async( + def create_with_http_info( self, weight: int, priority: int, enabled: bool, friendly_name: str, sip_url: str, - ) -> OriginationUrlInstance: + ) -> ApiResponse: """ - Asynchronously create the OriginationUrlInstance + Create the OriginationUrlInstance and return response metadata :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. @@ -474,7 +790,33 @@ async def create_async( :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. - :returns: The created OriginationUrlInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -492,14 +834,71 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Asynchronously create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + payload, _, _ = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> ApiResponse: + """ + Asynchronously create the OriginationUrlInstance and return response metadata + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -550,6 +949,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -569,6 +1018,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -595,6 +1045,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -603,6 +1054,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OriginationUrlInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -634,7 +1135,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return OriginationUrlPage(self._version, response, self._solution) + return OriginationUrlPage(self._version, response, solution=self._solution) async def page_async( self, @@ -667,7 +1168,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return OriginationUrlPage(self._version, response, self._solution) + return OriginationUrlPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OriginationUrlPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OriginationUrlPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OriginationUrlPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OriginationUrlPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> OriginationUrlPage: """ @@ -679,7 +1250,7 @@ def get_page(self, target_url: str) -> OriginationUrlPage: :returns: Page of OriginationUrlInstance """ response = self._version.domain.twilio.request("GET", target_url) - return OriginationUrlPage(self._version, response, self._solution) + return OriginationUrlPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> OriginationUrlPage: """ @@ -691,7 +1262,7 @@ async def get_page_async(self, target_url: str) -> OriginationUrlPage: :returns: Page of OriginationUrlInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return OriginationUrlPage(self._version, response, self._solution) + return OriginationUrlPage(self._version, response, solution=self._solution) def get(self, sid: str) -> OriginationUrlContext: """ diff --git a/twilio/rest/trunking/v1/trunk/phone_number.py b/twilio/rest/trunking/v1/trunk/phone_number.py index a7c3dbe20d..20abc377fb 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,7 +36,7 @@ class AddressRequirement(object): :ivar address_requirements: :ivar api_version: The API version used to start a new TwiML session. :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. - :ivar capabilities: The set of Boolean properties that indicate whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar capabilities: :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar friendly_name: The string that you assigned to describe the resource. @@ -74,7 +75,7 @@ def __init__( ] = payload.get("address_requirements") self.api_version: Optional[str] = payload.get("api_version") self.beta: Optional[bool] = payload.get("beta") - self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.capabilities: Optional[str] = payload.get("capabilities") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -109,6 +110,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -145,6 +147,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -163,6 +183,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -192,6 +230,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/PhoneNumbers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -199,10 +251,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -211,27 +285,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> PhoneNumberInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the PhoneNumberInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = self._fetch() return PhoneNumberInstance( self._version, payload, @@ -239,22 +329,46 @@ def fetch(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> PhoneNumberInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + payload, _, _ = await self._fetch_async() return PhoneNumberInstance( self._version, payload, @@ -262,6 +376,22 @@ async def fetch_async(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -280,6 +410,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -311,13 +442,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) - def create(self, phone_number_sid: str) -> PhoneNumberInstance: + def _create(self, phone_number_sid: str) -> tuple: """ - Create the PhoneNumberInstance + Internal helper for create operation - :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. - - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -331,21 +461,43 @@ def create(self, phone_number_sid: str) -> PhoneNumberInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = self._create(phone_number_sid=phone_number_sid) return PhoneNumberInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + def create_with_http_info(self, phone_number_sid: str) -> ApiResponse: """ - Asynchronously create the PhoneNumberInstance + Create the PhoneNumberInstance and return response metadata :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. - :returns: The created PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number_sid=phone_number_sid) + instance = PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -359,14 +511,39 @@ async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = await self._create_async(phone_number_sid=phone_number_sid) return PhoneNumberInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async(self, phone_number_sid: str) -> ApiResponse: + """ + Asynchronously create the PhoneNumberInstance and return response metadata + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number_sid=phone_number_sid + ) + instance = PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -417,6 +594,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -436,6 +663,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -462,6 +690,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -470,6 +699,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -501,7 +780,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -534,7 +813,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PhoneNumberPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PhoneNumberPage: """ @@ -546,7 +895,7 @@ def get_page(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PhoneNumberPage: """ @@ -558,7 +907,7 @@ async def get_page_async(self, target_url: str) -> PhoneNumberPage: :returns: Page of PhoneNumberInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PhoneNumberPage(self._version, response, self._solution) + return PhoneNumberPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PhoneNumberContext: """ diff --git a/twilio/rest/trunking/v1/trunk/recording.py b/twilio/rest/trunking/v1/trunk/recording.py index 0507662f24..5e29ae8205 100644 --- a/twilio/rest/trunking/v1/trunk/recording.py +++ b/twilio/rest/trunking/v1/trunk/recording.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], trunk_sid: str): self._solution = { "trunk_sid": trunk_sid, } + self._context: Optional[RecordingContext] = None @property @@ -82,6 +84,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, mode: Union["RecordingInstance.RecordingMode", object] = values.unset, @@ -118,6 +138,42 @@ async def update_async( trim=trim, ) + def update_with_http_info( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + mode=mode, + trim=trim, + ) + + async def update_with_http_info_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + mode=mode, + trim=trim, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,60 +201,106 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/Recording".format(**self._solution) - def fetch(self) -> RecordingInstance: + def _fetch(self) -> tuple: """ - Fetch the RecordingInstance + Internal helper for fetch operation - - :returns: The fetched RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() return RecordingInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"], ) - async def fetch_async(self) -> RecordingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() return RecordingInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, mode: Union["RecordingInstance.RecordingMode", object] = values.unset, trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, - ) -> RecordingInstance: + ) -> tuple: """ - Update the RecordingInstance - - :param mode: - :param trim: + Internal helper for update operation - :returns: The updated RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -213,26 +315,57 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + payload, _, _ = self._update(mode=mode, trim=trim) return RecordingInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def update_async( + def update_with_http_info( self, mode: Union["RecordingInstance.RecordingMode", object] = values.unset, trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, - ) -> RecordingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the RecordingInstance + Update the RecordingInstance and return response metadata :param mode: :param trim: - :returns: The updated RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(mode=mode, trim=trim) + instance = RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -247,14 +380,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + payload, _, _ = await self._update_async(mode=mode, trim=trim) return RecordingInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def update_with_http_info_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(mode=mode, trim=trim) + instance = RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/trusthub/v1/__init__.py b/twilio/rest/trusthub/v1/__init__.py index 596c5ea758..cfe702b2ed 100644 --- a/twilio/rest/trusthub/v1/__init__.py +++ b/twilio/rest/trusthub/v1/__init__.py @@ -15,6 +15,16 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.trusthub.v1.a2_p_brand_registration import A2PBrandRegistrationList +from twilio.rest.trusthub.v1.a2_p_brand_registration_embedded_session import ( + A2PBrandRegistrationEmbeddedSessionList, +) +from twilio.rest.trusthub.v1.a2_p_campaign_registration import ( + A2PCampaignRegistrationList, +) +from twilio.rest.trusthub.v1.a2_p_campaign_registration_embedded_session import ( + A2PCampaignRegistrationEmbeddedSessionList, +) from twilio.rest.trusthub.v1.compliance_inquiries import ComplianceInquiriesList from twilio.rest.trusthub.v1.compliance_registration_inquiries import ( ComplianceRegistrationInquiriesList, @@ -23,12 +33,18 @@ ComplianceTollfreeInquiriesList, ) from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList +from twilio.rest.trusthub.v1.customer_profiles_provisional_copy import ( + CustomerProfilesProvisionalCopyList, +) from twilio.rest.trusthub.v1.end_user import EndUserList from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList from twilio.rest.trusthub.v1.policies import PoliciesList from twilio.rest.trusthub.v1.supporting_document import SupportingDocumentList from twilio.rest.trusthub.v1.supporting_document_type import SupportingDocumentTypeList from twilio.rest.trusthub.v1.trust_products import TrustProductsList +from twilio.rest.trusthub.v1.trust_products_provisional_copy import ( + TrustProductsProvisionalCopyList, +) class V1(Version): @@ -40,6 +56,8 @@ def __init__(self, domain: Domain): :param domain: The Twilio.trusthub domain """ super().__init__(domain, "v1") + self._a2_p_brand_registrations: Optional[A2PBrandRegistrationList] = None + self._a2_p_campaign_registrations: Optional[A2PCampaignRegistrationList] = None self._compliance_inquiries: Optional[ComplianceInquiriesList] = None self._compliance_registration_inquiries: Optional[ ComplianceRegistrationInquiriesList @@ -48,12 +66,62 @@ def __init__(self, domain: Domain): ComplianceTollfreeInquiriesList ] = None self._customer_profiles: Optional[CustomerProfilesList] = None + self._customer_profiles_provisional_copy: Optional[ + CustomerProfilesProvisionalCopyList + ] = None self._end_users: Optional[EndUserList] = None self._end_user_types: Optional[EndUserTypeList] = None self._policies: Optional[PoliciesList] = None self._supporting_documents: Optional[SupportingDocumentList] = None self._supporting_document_types: Optional[SupportingDocumentTypeList] = None self._trust_products: Optional[TrustProductsList] = None + self._trust_products_provisional_copy: Optional[ + TrustProductsProvisionalCopyList + ] = None + + @property + def a2_p_brand_registrations(self) -> A2PBrandRegistrationList: + if self._a2_p_brand_registrations is None: + self._a2_p_brand_registrations = A2PBrandRegistrationList(self) + return self._a2_p_brand_registrations + + def a2_p_brand_registration_embedded_sessions( + self, id: str, a2p_brand_registration_embedded_session_id: str = None + ): + """ + Access the A2PBrandRegistrationEmbeddedSessionList resource + + :param id: The unique identifier for the A2P Brand Registration. + + :param a2p_brand_registration_embedded_session_id: Optional instance ID to directly access A2PBrandRegistrationEmbeddedSessionContext + :returns: A2PBrandRegistrationEmbeddedSessionList instance if a2p_brand_registration_embedded_session_id is None, otherwise A2PBrandRegistrationEmbeddedSessionContext + """ + list_instance = A2PBrandRegistrationEmbeddedSessionList(self, id) + if a2p_brand_registration_embedded_session_id is not None: + return list_instance(a2p_brand_registration_embedded_session_id) + return list_instance + + @property + def a2_p_campaign_registrations(self) -> A2PCampaignRegistrationList: + if self._a2_p_campaign_registrations is None: + self._a2_p_campaign_registrations = A2PCampaignRegistrationList(self) + return self._a2_p_campaign_registrations + + def a2_p_campaign_registration_embedded_sessions( + self, id: str, a2p_campaign_registration_embedded_session_id: str = None + ): + """ + Access the A2PCampaignRegistrationEmbeddedSessionList resource + + :param id: The unique identifier for the A2P Campaign Registration. This can be either an A2P Campaign Registration ID (formatted `tri1.us1.account.AC.../registration.BU...`) returned from the Initialize Campaign endpoint, or a Messaging Service SID (`MG...`) for campaigns created outside the embeddable. + + :param a2p_campaign_registration_embedded_session_id: Optional instance ID to directly access A2PCampaignRegistrationEmbeddedSessionContext + :returns: A2PCampaignRegistrationEmbeddedSessionList instance if a2p_campaign_registration_embedded_session_id is None, otherwise A2PCampaignRegistrationEmbeddedSessionContext + """ + list_instance = A2PCampaignRegistrationEmbeddedSessionList(self, id) + if a2p_campaign_registration_embedded_session_id is not None: + return list_instance(a2p_campaign_registration_embedded_session_id) + return list_instance @property def compliance_inquiries(self) -> ComplianceInquiriesList: @@ -81,6 +149,14 @@ def customer_profiles(self) -> CustomerProfilesList: self._customer_profiles = CustomerProfilesList(self) return self._customer_profiles + @property + def customer_profiles_provisional_copy(self) -> CustomerProfilesProvisionalCopyList: + if self._customer_profiles_provisional_copy is None: + self._customer_profiles_provisional_copy = ( + CustomerProfilesProvisionalCopyList(self) + ) + return self._customer_profiles_provisional_copy + @property def end_users(self) -> EndUserList: if self._end_users is None: @@ -117,6 +193,14 @@ def trust_products(self) -> TrustProductsList: self._trust_products = TrustProductsList(self) return self._trust_products + @property + def trust_products_provisional_copy(self) -> TrustProductsProvisionalCopyList: + if self._trust_products_provisional_copy is None: + self._trust_products_provisional_copy = TrustProductsProvisionalCopyList( + self + ) + return self._trust_products_provisional_copy + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/trusthub/v1/a2_p_brand_registration.py b/twilio/rest/trusthub/v1/a2_p_brand_registration.py new file mode 100644 index 0000000000..de712d4fad --- /dev/null +++ b/twilio/rest/trusthub/v1/a2_p_brand_registration.py @@ -0,0 +1,436 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class A2PBrandRegistrationInstance(InstanceResource): + + class TrusthubV1A2pBrandRegistrationRequest(object): + """ + :ivar brand_type: The type of brand being registered. + :ivar theme_set_id: Theme ID for styling the inquiry form. + :ivar friendly_name: A human-readable name for the brand registration. + :ivar notification_email: The email address to receive notifications about the registration. + :ivar business_name: The legal name of the business. + :ivar business_registration_authority: The authority with which the business is registered. + :ivar business_registration_number: The business registration number (e.g., EIN, CBN, ACN). Maximum 21 characters. + :ivar business_industry: The industry of the business. + :ivar business_website: The business website URL (must use https://). + :ivar business_type: The type of business entity. + :ivar business_stock_symbol: The stock symbol for publicly traded companies. + :ivar business_stock_exchange: The stock exchange where the business is listed. + :ivar business_tax_exempt_status: Nonprofit/political organization tax-exempt status per the U.S. tax code (e.g. 501c3, 501c1, 527). A value of 527 (political organization) requires a Campaign Verify token in brandExternalVettingToken. + :ivar brand_external_vetting_token: Campaign Verify token for externally vetted brands. + :ivar business_street_address: The street address of the business. + :ivar business_street_address2: Additional street address information. + :ivar business_city: The city of the business. + :ivar business_state_province_region: The state, province, or region of the business. + :ivar business_postal_code: The postal code of the business. + :ivar business_country: The two-letter ISO country code of the business. + :ivar business_contact_first_name: The first name of the business contact. + :ivar business_contact_last_name: The last name of the business contact. + :ivar business_contact_email: The email address of the business contact. + :ivar business_contact_phone: The phone number of the business contact in E.164 format. + :ivar authorized_contact_verification_email: The email address for authorized contact verification. + :ivar authorized_contact_mobile_phone_number_e164: The mobile phone number for authorized contact in E.164 format. + :ivar is_test: Whether this is a test brand registration. + :ivar skip_automatic_sec_vet: Whether to skip automatic secondary vetting. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.brand_type: Optional["A2PBrandRegistrationInstance.str"] = payload.get( + "brandType" + ) + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.notification_email: Optional[str] = payload.get("notificationEmail") + self.business_name: Optional[str] = payload.get("businessName") + self.business_registration_authority: Optional[str] = payload.get( + "businessRegistrationAuthority" + ) + self.business_registration_number: Optional[str] = payload.get( + "businessRegistrationNumber" + ) + self.business_industry: Optional[str] = payload.get("businessIndustry") + self.business_website: Optional[str] = payload.get("businessWebsite") + self.business_type: Optional[str] = payload.get("businessType") + self.business_stock_symbol: Optional[str] = payload.get( + "businessStockSymbol" + ) + self.business_stock_exchange: Optional[str] = payload.get( + "businessStockExchange" + ) + self.business_tax_exempt_status: Optional[str] = payload.get( + "businessTaxExemptStatus" + ) + self.brand_external_vetting_token: Optional[str] = payload.get( + "brandExternalVettingToken" + ) + self.business_street_address: Optional[str] = payload.get( + "businessStreetAddress" + ) + self.business_street_address2: Optional[str] = payload.get( + "businessStreetAddress2" + ) + self.business_city: Optional[str] = payload.get("businessCity") + self.business_state_province_region: Optional[str] = payload.get( + "businessStateProvinceRegion" + ) + self.business_postal_code: Optional[str] = payload.get("businessPostalCode") + self.business_country: Optional[str] = payload.get("businessCountry") + self.business_contact_first_name: Optional[str] = payload.get( + "businessContactFirstName" + ) + self.business_contact_last_name: Optional[str] = payload.get( + "businessContactLastName" + ) + self.business_contact_email: Optional[str] = payload.get( + "businessContactEmail" + ) + self.business_contact_phone: Optional[str] = payload.get( + "businessContactPhone" + ) + self.authorized_contact_verification_email: Optional[str] = payload.get( + "authorizedContactVerificationEmail" + ) + self.authorized_contact_mobile_phone_number_e164: Optional[str] = ( + payload.get("authorizedContactMobilePhoneNumberE164") + ) + self.is_test: Optional[bool] = payload.get("isTest") + self.skip_automatic_sec_vet: Optional[bool] = payload.get( + "skipAutomaticSecVet" + ) + + def to_dict(self): + return { + "brandType": self.brand_type, + "themeSetId": self.theme_set_id, + "friendlyName": self.friendly_name, + "notificationEmail": self.notification_email, + "businessName": self.business_name, + "businessRegistrationAuthority": self.business_registration_authority, + "businessRegistrationNumber": self.business_registration_number, + "businessIndustry": self.business_industry, + "businessWebsite": self.business_website, + "businessType": self.business_type, + "businessStockSymbol": self.business_stock_symbol, + "businessStockExchange": self.business_stock_exchange, + "businessTaxExemptStatus": self.business_tax_exempt_status, + "brandExternalVettingToken": self.brand_external_vetting_token, + "businessStreetAddress": self.business_street_address, + "businessStreetAddress2": self.business_street_address2, + "businessCity": self.business_city, + "businessStateProvinceRegion": self.business_state_province_region, + "businessPostalCode": self.business_postal_code, + "businessCountry": self.business_country, + "businessContactFirstName": self.business_contact_first_name, + "businessContactLastName": self.business_contact_last_name, + "businessContactEmail": self.business_contact_email, + "businessContactPhone": self.business_contact_phone, + "authorizedContactVerificationEmail": self.authorized_contact_verification_email, + "authorizedContactMobilePhoneNumberE164": self.authorized_contact_mobile_phone_number_e164, + "isTest": self.is_test, + "skipAutomaticSecVet": self.skip_automatic_sec_vet, + } + + """ + :ivar id: The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + :ivar session_id: The Persona inquiry ID used to start the embedded compliance session. + :ivar session_token: The Persona session token for embedding the compliance UI. Expires in 24 hours. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Trusthub.V1.A2PBrandRegistrationInstance>" + + +class A2PBrandRegistrationList(ListResource): + + class TrusthubV1A2pBrandRegistrationRequest(object): + """ + :ivar brand_type: The type of brand being registered. + :ivar theme_set_id: Theme ID for styling the inquiry form. + :ivar friendly_name: A human-readable name for the brand registration. + :ivar notification_email: The email address to receive notifications about the registration. + :ivar business_name: The legal name of the business. + :ivar business_registration_authority: The authority with which the business is registered. + :ivar business_registration_number: The business registration number (e.g., EIN, CBN, ACN). Maximum 21 characters. + :ivar business_industry: The industry of the business. + :ivar business_website: The business website URL (must use https://). + :ivar business_type: The type of business entity. + :ivar business_stock_symbol: The stock symbol for publicly traded companies. + :ivar business_stock_exchange: The stock exchange where the business is listed. + :ivar business_tax_exempt_status: Nonprofit/political organization tax-exempt status per the U.S. tax code (e.g. 501c3, 501c1, 527). A value of 527 (political organization) requires a Campaign Verify token in brandExternalVettingToken. + :ivar brand_external_vetting_token: Campaign Verify token for externally vetted brands. + :ivar business_street_address: The street address of the business. + :ivar business_street_address2: Additional street address information. + :ivar business_city: The city of the business. + :ivar business_state_province_region: The state, province, or region of the business. + :ivar business_postal_code: The postal code of the business. + :ivar business_country: The two-letter ISO country code of the business. + :ivar business_contact_first_name: The first name of the business contact. + :ivar business_contact_last_name: The last name of the business contact. + :ivar business_contact_email: The email address of the business contact. + :ivar business_contact_phone: The phone number of the business contact in E.164 format. + :ivar authorized_contact_verification_email: The email address for authorized contact verification. + :ivar authorized_contact_mobile_phone_number_e164: The mobile phone number for authorized contact in E.164 format. + :ivar is_test: Whether this is a test brand registration. + :ivar skip_automatic_sec_vet: Whether to skip automatic secondary vetting. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.brand_type: Optional["A2PBrandRegistrationInstance.str"] = payload.get( + "brandType" + ) + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.friendly_name: Optional[str] = payload.get("friendlyName") + self.notification_email: Optional[str] = payload.get("notificationEmail") + self.business_name: Optional[str] = payload.get("businessName") + self.business_registration_authority: Optional[str] = payload.get( + "businessRegistrationAuthority" + ) + self.business_registration_number: Optional[str] = payload.get( + "businessRegistrationNumber" + ) + self.business_industry: Optional[str] = payload.get("businessIndustry") + self.business_website: Optional[str] = payload.get("businessWebsite") + self.business_type: Optional[str] = payload.get("businessType") + self.business_stock_symbol: Optional[str] = payload.get( + "businessStockSymbol" + ) + self.business_stock_exchange: Optional[str] = payload.get( + "businessStockExchange" + ) + self.business_tax_exempt_status: Optional[str] = payload.get( + "businessTaxExemptStatus" + ) + self.brand_external_vetting_token: Optional[str] = payload.get( + "brandExternalVettingToken" + ) + self.business_street_address: Optional[str] = payload.get( + "businessStreetAddress" + ) + self.business_street_address2: Optional[str] = payload.get( + "businessStreetAddress2" + ) + self.business_city: Optional[str] = payload.get("businessCity") + self.business_state_province_region: Optional[str] = payload.get( + "businessStateProvinceRegion" + ) + self.business_postal_code: Optional[str] = payload.get("businessPostalCode") + self.business_country: Optional[str] = payload.get("businessCountry") + self.business_contact_first_name: Optional[str] = payload.get( + "businessContactFirstName" + ) + self.business_contact_last_name: Optional[str] = payload.get( + "businessContactLastName" + ) + self.business_contact_email: Optional[str] = payload.get( + "businessContactEmail" + ) + self.business_contact_phone: Optional[str] = payload.get( + "businessContactPhone" + ) + self.authorized_contact_verification_email: Optional[str] = payload.get( + "authorizedContactVerificationEmail" + ) + self.authorized_contact_mobile_phone_number_e164: Optional[str] = ( + payload.get("authorizedContactMobilePhoneNumberE164") + ) + self.is_test: Optional[bool] = payload.get("isTest") + self.skip_automatic_sec_vet: Optional[bool] = payload.get( + "skipAutomaticSecVet" + ) + + def to_dict(self): + return { + "brandType": self.brand_type, + "themeSetId": self.theme_set_id, + "friendlyName": self.friendly_name, + "notificationEmail": self.notification_email, + "businessName": self.business_name, + "businessRegistrationAuthority": self.business_registration_authority, + "businessRegistrationNumber": self.business_registration_number, + "businessIndustry": self.business_industry, + "businessWebsite": self.business_website, + "businessType": self.business_type, + "businessStockSymbol": self.business_stock_symbol, + "businessStockExchange": self.business_stock_exchange, + "businessTaxExemptStatus": self.business_tax_exempt_status, + "brandExternalVettingToken": self.brand_external_vetting_token, + "businessStreetAddress": self.business_street_address, + "businessStreetAddress2": self.business_street_address2, + "businessCity": self.business_city, + "businessStateProvinceRegion": self.business_state_province_region, + "businessPostalCode": self.business_postal_code, + "businessCountry": self.business_country, + "businessContactFirstName": self.business_contact_first_name, + "businessContactLastName": self.business_contact_last_name, + "businessContactEmail": self.business_contact_email, + "businessContactPhone": self.business_contact_phone, + "authorizedContactVerificationEmail": self.authorized_contact_verification_email, + "authorizedContactMobilePhoneNumberE164": self.authorized_contact_mobile_phone_number_e164, + "isTest": self.is_test, + "skipAutomaticSecVet": self.skip_automatic_sec_vet, + } + + def __init__(self, version: Version): + """ + Initialize the A2PBrandRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/A2PBrandRegistrations" + + def _create( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trusthub_v1_a2p_brand_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> A2PBrandRegistrationInstance: + """ + Create the A2PBrandRegistrationInstance + + :param trusthub_v1_a2p_brand_registration_request: + + :returns: The created A2PBrandRegistrationInstance + """ + payload, _, _ = self._create( + trusthub_v1_a2p_brand_registration_request=trusthub_v1_a2p_brand_registration_request + ) + return A2PBrandRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> ApiResponse: + """ + Create the A2PBrandRegistrationInstance and return response metadata + + :param trusthub_v1_a2p_brand_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + trusthub_v1_a2p_brand_registration_request=trusthub_v1_a2p_brand_registration_request + ) + instance = A2PBrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trusthub_v1_a2p_brand_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> A2PBrandRegistrationInstance: + """ + Asynchronously create the A2PBrandRegistrationInstance + + :param trusthub_v1_a2p_brand_registration_request: + + :returns: The created A2PBrandRegistrationInstance + """ + payload, _, _ = await self._create_async( + trusthub_v1_a2p_brand_registration_request=trusthub_v1_a2p_brand_registration_request + ) + return A2PBrandRegistrationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + trusthub_v1_a2p_brand_registration_request: TrusthubV1A2pBrandRegistrationRequest, + ) -> ApiResponse: + """ + Asynchronously create the A2PBrandRegistrationInstance and return response metadata + + :param trusthub_v1_a2p_brand_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + trusthub_v1_a2p_brand_registration_request=trusthub_v1_a2p_brand_registration_request + ) + instance = A2PBrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.A2PBrandRegistrationList>" diff --git a/twilio/rest/trusthub/v1/a2_p_brand_registration_embedded_session.py b/twilio/rest/trusthub/v1/a2_p_brand_registration_embedded_session.py new file mode 100644 index 0000000000..6f69a8534c --- /dev/null +++ b/twilio/rest/trusthub/v1/a2_p_brand_registration_embedded_session.py @@ -0,0 +1,164 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class A2PBrandRegistrationEmbeddedSessionInstance(InstanceResource): + """ + :ivar id: The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + :ivar session_id: The Persona inquiry ID used to start the embedded compliance session. + :ivar session_token: The Persona session token for embedding the compliance UI. Expires in 24 hours. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + self._solution = { + "id": id or self.id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.A2PBrandRegistrationEmbeddedSessionInstance {}>".format( + context + ) + + +class A2PBrandRegistrationEmbeddedSessionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the A2PBrandRegistrationEmbeddedSessionList + + :param version: Version that contains the resource + :param id: The unique identifier for the A2P Brand Registration. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/A2PBrandRegistrations/{id}/EmbeddedSessions".format( + **self._solution + ) + + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> A2PBrandRegistrationEmbeddedSessionInstance: + """ + Create the A2PBrandRegistrationEmbeddedSessionInstance + + + :returns: The created A2PBrandRegistrationEmbeddedSessionInstance + """ + payload, _, _ = self._create() + return A2PBrandRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the A2PBrandRegistrationEmbeddedSessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = A2PBrandRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> A2PBrandRegistrationEmbeddedSessionInstance: + """ + Asynchronously create the A2PBrandRegistrationEmbeddedSessionInstance + + + :returns: The created A2PBrandRegistrationEmbeddedSessionInstance + """ + payload, _, _ = await self._create_async() + return A2PBrandRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the A2PBrandRegistrationEmbeddedSessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = A2PBrandRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.A2PBrandRegistrationEmbeddedSessionList>" diff --git a/twilio/rest/trusthub/v1/a2_p_campaign_registration.py b/twilio/rest/trusthub/v1/a2_p_campaign_registration.py new file mode 100644 index 0000000000..b3f0dd160b --- /dev/null +++ b/twilio/rest/trusthub/v1/a2_p_campaign_registration.py @@ -0,0 +1,402 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class A2PCampaignRegistrationInstance(InstanceResource): + + class TrusthubV1A2pCampaignRegistrationRequest(object): + """ + :ivar a2p_brand_registration_sid: The legacy Twilio A2P Brand SID (BN-prefixed) for the brand this campaign is registered under. This is a different identifier from the `id` returned by the Initialize Brand endpoint (which is formatted as `tri1.us1.account.AC.../registration.BU...`). Retrieve the BN brand SID via [GET /v1/a2p/BrandRegistrations/{Sid}](https://www.twilio.com/docs/messaging/api/brand-registration-resource) on `messaging.twilio.com`. + :ivar messaging_service_sid: The SID of the Messaging Service. + :ivar theme_set_id: Theme ID for styling the inquiry form. + :ivar use_case_categories: The categories of the messaging use case. + :ivar use_case_description: A description of the messaging use case. + :ivar use_case_sample_message1: A sample message for the use case. + :ivar use_case_sample_message2: A second sample message for the use case. + :ivar use_case_sample_message3: A third sample message for the use case. + :ivar use_case_sample_message4: A fourth sample message for the use case. + :ivar use_case_sample_message5: A fifth sample message for the use case. + :ivar use_case_opt_in_types: The opt-in methods for the use case. + :ivar use_case_opt_in_description: A description of the opt-in process. + :ivar has_embedded_links: Whether messages will contain embedded links. + :ivar has_embedded_phone: Whether messages will contain embedded phone numbers. + :ivar embedded_url_sample: A sample URL that will be embedded in messages (must use https://). + :ivar direct_lending: Whether the campaign involves direct lending. + :ivar age_gated: Whether the content is age-gated. + :ivar privacy_policy_url: The URL to the privacy policy. + :ivar terms_and_conditions_url: The URL to the terms and conditions. + :ivar opt_in_keywords: Keywords users can text to opt in. + :ivar opt_in_message_sample: A sample opt-in confirmation message. + :ivar opt_out_keywords: Keywords users can text to opt out. + :ivar opt_out_message_sample: A sample opt-out confirmation message. + :ivar help_keywords: Keywords users can text for help. + :ivar help_message_sample: A sample help message. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.a2p_brand_registration_sid: Optional[str] = payload.get( + "a2pBrandRegistrationSid" + ) + self.messaging_service_sid: Optional[str] = payload.get( + "messagingServiceSid" + ) + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.use_case_categories: Optional[List[str]] = payload.get( + "useCaseCategories" + ) + self.use_case_description: Optional[str] = payload.get("useCaseDescription") + self.use_case_sample_message1: Optional[str] = payload.get( + "useCaseSampleMessage1" + ) + self.use_case_sample_message2: Optional[str] = payload.get( + "useCaseSampleMessage2" + ) + self.use_case_sample_message3: Optional[str] = payload.get( + "useCaseSampleMessage3" + ) + self.use_case_sample_message4: Optional[str] = payload.get( + "useCaseSampleMessage4" + ) + self.use_case_sample_message5: Optional[str] = payload.get( + "useCaseSampleMessage5" + ) + self.use_case_opt_in_types: Optional[List[str]] = payload.get( + "useCaseOptInTypes" + ) + self.use_case_opt_in_description: Optional[str] = payload.get( + "useCaseOptInDescription" + ) + self.has_embedded_links: Optional[bool] = payload.get("hasEmbeddedLinks") + self.has_embedded_phone: Optional[bool] = payload.get("hasEmbeddedPhone") + self.embedded_url_sample: Optional[str] = payload.get("embeddedUrlSample") + self.direct_lending: Optional[bool] = payload.get("directLending") + self.age_gated: Optional[bool] = payload.get("ageGated") + self.privacy_policy_url: Optional[str] = payload.get("privacyPolicyUrl") + self.terms_and_conditions_url: Optional[str] = payload.get( + "termsAndConditionsUrl" + ) + self.opt_in_keywords: Optional[List[str]] = payload.get("optInKeywords") + self.opt_in_message_sample: Optional[str] = payload.get( + "optInMessageSample" + ) + self.opt_out_keywords: Optional[List[str]] = payload.get("optOutKeywords") + self.opt_out_message_sample: Optional[str] = payload.get( + "optOutMessageSample" + ) + self.help_keywords: Optional[List[str]] = payload.get("helpKeywords") + self.help_message_sample: Optional[str] = payload.get("helpMessageSample") + + def to_dict(self): + return { + "a2pBrandRegistrationSid": self.a2p_brand_registration_sid, + "messagingServiceSid": self.messaging_service_sid, + "themeSetId": self.theme_set_id, + "useCaseCategories": self.use_case_categories, + "useCaseDescription": self.use_case_description, + "useCaseSampleMessage1": self.use_case_sample_message1, + "useCaseSampleMessage2": self.use_case_sample_message2, + "useCaseSampleMessage3": self.use_case_sample_message3, + "useCaseSampleMessage4": self.use_case_sample_message4, + "useCaseSampleMessage5": self.use_case_sample_message5, + "useCaseOptInTypes": self.use_case_opt_in_types, + "useCaseOptInDescription": self.use_case_opt_in_description, + "hasEmbeddedLinks": self.has_embedded_links, + "hasEmbeddedPhone": self.has_embedded_phone, + "embeddedUrlSample": self.embedded_url_sample, + "directLending": self.direct_lending, + "ageGated": self.age_gated, + "privacyPolicyUrl": self.privacy_policy_url, + "termsAndConditionsUrl": self.terms_and_conditions_url, + "optInKeywords": self.opt_in_keywords, + "optInMessageSample": self.opt_in_message_sample, + "optOutKeywords": self.opt_out_keywords, + "optOutMessageSample": self.opt_out_message_sample, + "helpKeywords": self.help_keywords, + "helpMessageSample": self.help_message_sample, + } + + """ + :ivar id: The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + :ivar session_id: The Persona inquiry ID used to start the embedded compliance session. + :ivar session_token: The Persona session token for embedding the compliance UI. Expires in 24 hours. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Trusthub.V1.A2PCampaignRegistrationInstance>" + + +class A2PCampaignRegistrationList(ListResource): + + class TrusthubV1A2pCampaignRegistrationRequest(object): + """ + :ivar a2p_brand_registration_sid: The legacy Twilio A2P Brand SID (BN-prefixed) for the brand this campaign is registered under. This is a different identifier from the `id` returned by the Initialize Brand endpoint (which is formatted as `tri1.us1.account.AC.../registration.BU...`). Retrieve the BN brand SID via [GET /v1/a2p/BrandRegistrations/{Sid}](https://www.twilio.com/docs/messaging/api/brand-registration-resource) on `messaging.twilio.com`. + :ivar messaging_service_sid: The SID of the Messaging Service. + :ivar theme_set_id: Theme ID for styling the inquiry form. + :ivar use_case_categories: The categories of the messaging use case. + :ivar use_case_description: A description of the messaging use case. + :ivar use_case_sample_message1: A sample message for the use case. + :ivar use_case_sample_message2: A second sample message for the use case. + :ivar use_case_sample_message3: A third sample message for the use case. + :ivar use_case_sample_message4: A fourth sample message for the use case. + :ivar use_case_sample_message5: A fifth sample message for the use case. + :ivar use_case_opt_in_types: The opt-in methods for the use case. + :ivar use_case_opt_in_description: A description of the opt-in process. + :ivar has_embedded_links: Whether messages will contain embedded links. + :ivar has_embedded_phone: Whether messages will contain embedded phone numbers. + :ivar embedded_url_sample: A sample URL that will be embedded in messages (must use https://). + :ivar direct_lending: Whether the campaign involves direct lending. + :ivar age_gated: Whether the content is age-gated. + :ivar privacy_policy_url: The URL to the privacy policy. + :ivar terms_and_conditions_url: The URL to the terms and conditions. + :ivar opt_in_keywords: Keywords users can text to opt in. + :ivar opt_in_message_sample: A sample opt-in confirmation message. + :ivar opt_out_keywords: Keywords users can text to opt out. + :ivar opt_out_message_sample: A sample opt-out confirmation message. + :ivar help_keywords: Keywords users can text for help. + :ivar help_message_sample: A sample help message. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.a2p_brand_registration_sid: Optional[str] = payload.get( + "a2pBrandRegistrationSid" + ) + self.messaging_service_sid: Optional[str] = payload.get( + "messagingServiceSid" + ) + self.theme_set_id: Optional[str] = payload.get("themeSetId") + self.use_case_categories: Optional[List[str]] = payload.get( + "useCaseCategories" + ) + self.use_case_description: Optional[str] = payload.get("useCaseDescription") + self.use_case_sample_message1: Optional[str] = payload.get( + "useCaseSampleMessage1" + ) + self.use_case_sample_message2: Optional[str] = payload.get( + "useCaseSampleMessage2" + ) + self.use_case_sample_message3: Optional[str] = payload.get( + "useCaseSampleMessage3" + ) + self.use_case_sample_message4: Optional[str] = payload.get( + "useCaseSampleMessage4" + ) + self.use_case_sample_message5: Optional[str] = payload.get( + "useCaseSampleMessage5" + ) + self.use_case_opt_in_types: Optional[List[str]] = payload.get( + "useCaseOptInTypes" + ) + self.use_case_opt_in_description: Optional[str] = payload.get( + "useCaseOptInDescription" + ) + self.has_embedded_links: Optional[bool] = payload.get("hasEmbeddedLinks") + self.has_embedded_phone: Optional[bool] = payload.get("hasEmbeddedPhone") + self.embedded_url_sample: Optional[str] = payload.get("embeddedUrlSample") + self.direct_lending: Optional[bool] = payload.get("directLending") + self.age_gated: Optional[bool] = payload.get("ageGated") + self.privacy_policy_url: Optional[str] = payload.get("privacyPolicyUrl") + self.terms_and_conditions_url: Optional[str] = payload.get( + "termsAndConditionsUrl" + ) + self.opt_in_keywords: Optional[List[str]] = payload.get("optInKeywords") + self.opt_in_message_sample: Optional[str] = payload.get( + "optInMessageSample" + ) + self.opt_out_keywords: Optional[List[str]] = payload.get("optOutKeywords") + self.opt_out_message_sample: Optional[str] = payload.get( + "optOutMessageSample" + ) + self.help_keywords: Optional[List[str]] = payload.get("helpKeywords") + self.help_message_sample: Optional[str] = payload.get("helpMessageSample") + + def to_dict(self): + return { + "a2pBrandRegistrationSid": self.a2p_brand_registration_sid, + "messagingServiceSid": self.messaging_service_sid, + "themeSetId": self.theme_set_id, + "useCaseCategories": self.use_case_categories, + "useCaseDescription": self.use_case_description, + "useCaseSampleMessage1": self.use_case_sample_message1, + "useCaseSampleMessage2": self.use_case_sample_message2, + "useCaseSampleMessage3": self.use_case_sample_message3, + "useCaseSampleMessage4": self.use_case_sample_message4, + "useCaseSampleMessage5": self.use_case_sample_message5, + "useCaseOptInTypes": self.use_case_opt_in_types, + "useCaseOptInDescription": self.use_case_opt_in_description, + "hasEmbeddedLinks": self.has_embedded_links, + "hasEmbeddedPhone": self.has_embedded_phone, + "embeddedUrlSample": self.embedded_url_sample, + "directLending": self.direct_lending, + "ageGated": self.age_gated, + "privacyPolicyUrl": self.privacy_policy_url, + "termsAndConditionsUrl": self.terms_and_conditions_url, + "optInKeywords": self.opt_in_keywords, + "optInMessageSample": self.opt_in_message_sample, + "optOutKeywords": self.opt_out_keywords, + "optOutMessageSample": self.opt_out_message_sample, + "helpKeywords": self.help_keywords, + "helpMessageSample": self.help_message_sample, + } + + def __init__(self, version: Version): + """ + Initialize the A2PCampaignRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/A2PCampaignRegistrations" + + def _create( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trusthub_v1_a2p_campaign_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> A2PCampaignRegistrationInstance: + """ + Create the A2PCampaignRegistrationInstance + + :param trusthub_v1_a2p_campaign_registration_request: + + :returns: The created A2PCampaignRegistrationInstance + """ + payload, _, _ = self._create( + trusthub_v1_a2p_campaign_registration_request=trusthub_v1_a2p_campaign_registration_request + ) + return A2PCampaignRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> ApiResponse: + """ + Create the A2PCampaignRegistrationInstance and return response metadata + + :param trusthub_v1_a2p_campaign_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + trusthub_v1_a2p_campaign_registration_request=trusthub_v1_a2p_campaign_registration_request + ) + instance = A2PCampaignRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = trusthub_v1_a2p_campaign_registration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> A2PCampaignRegistrationInstance: + """ + Asynchronously create the A2PCampaignRegistrationInstance + + :param trusthub_v1_a2p_campaign_registration_request: + + :returns: The created A2PCampaignRegistrationInstance + """ + payload, _, _ = await self._create_async( + trusthub_v1_a2p_campaign_registration_request=trusthub_v1_a2p_campaign_registration_request + ) + return A2PCampaignRegistrationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + trusthub_v1_a2p_campaign_registration_request: TrusthubV1A2pCampaignRegistrationRequest, + ) -> ApiResponse: + """ + Asynchronously create the A2PCampaignRegistrationInstance and return response metadata + + :param trusthub_v1_a2p_campaign_registration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + trusthub_v1_a2p_campaign_registration_request=trusthub_v1_a2p_campaign_registration_request + ) + instance = A2PCampaignRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.A2PCampaignRegistrationList>" diff --git a/twilio/rest/trusthub/v1/a2_p_campaign_registration_embedded_session.py b/twilio/rest/trusthub/v1/a2_p_campaign_registration_embedded_session.py new file mode 100644 index 0000000000..ea8b150b69 --- /dev/null +++ b/twilio/rest/trusthub/v1/a2_p_campaign_registration_embedded_session.py @@ -0,0 +1,164 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class A2PCampaignRegistrationEmbeddedSessionInstance(InstanceResource): + """ + :ivar id: The unique A2P Brand or Campaign Registration identifier, formatted as `tri1.us1.account.AC.../registration.BU...`. + :ivar session_id: The Persona inquiry ID used to start the embedded compliance session. + :ivar session_token: The Persona session token for embedding the compliance UI. Expires in 24 hours. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.session_id: Optional[str] = payload.get("sessionId") + self.session_token: Optional[str] = payload.get("sessionToken") + + self._solution = { + "id": id or self.id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.A2PCampaignRegistrationEmbeddedSessionInstance {}>".format( + context + ) + + +class A2PCampaignRegistrationEmbeddedSessionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the A2PCampaignRegistrationEmbeddedSessionList + + :param version: Version that contains the resource + :param id: The unique identifier for the A2P Campaign Registration. This can be either an A2P Campaign Registration ID (formatted `tri1.us1.account.AC.../registration.BU...`) returned from the Initialize Campaign endpoint, or a Messaging Service SID (`MG...`) for campaigns created outside the embeddable. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/A2PCampaignRegistrations/{id}/EmbeddedSessions".format( + **self._solution + ) + + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> A2PCampaignRegistrationEmbeddedSessionInstance: + """ + Create the A2PCampaignRegistrationEmbeddedSessionInstance + + + :returns: The created A2PCampaignRegistrationEmbeddedSessionInstance + """ + payload, _, _ = self._create() + return A2PCampaignRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the A2PCampaignRegistrationEmbeddedSessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = A2PCampaignRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> A2PCampaignRegistrationEmbeddedSessionInstance: + """ + Asynchronously create the A2PCampaignRegistrationEmbeddedSessionInstance + + + :returns: The created A2PCampaignRegistrationEmbeddedSessionInstance + """ + payload, _, _ = await self._create_async() + return A2PCampaignRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the A2PCampaignRegistrationEmbeddedSessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = A2PCampaignRegistrationEmbeddedSessionInstance( + self._version, payload, id=self._solution["id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.A2PCampaignRegistrationEmbeddedSessionList>" diff --git a/twilio/rest/trusthub/v1/compliance_inquiries.py b/twilio/rest/trusthub/v1/compliance_inquiries.py index 3c1abd596a..107749eaa4 100644 --- a/twilio/rest/trusthub/v1/compliance_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "customer_id": customer_id or self.customer_id, } + self._context: Optional[ComplianceInquiriesContext] = None @property @@ -93,6 +95,38 @@ async def update_async( theme_set_id=theme_set_id, ) + def update_with_http_info( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ComplianceInquiriesInstance with HTTP info + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + async def update_with_http_info_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance with HTTP info + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -122,16 +156,14 @@ def __init__(self, version: Version, customer_id: str): **self._solution ) - def update( + def _update( self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset - ) -> ComplianceInquiriesInstance: + ) -> tuple: """ - Update the ComplianceInquiriesInstance + Internal helper for update operation - :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. - :param theme_set_id: Theme id for styling the inquiry form. - - :returns: The updated ComplianceInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -146,24 +178,55 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + payload, _, _ = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) return ComplianceInquiriesInstance( self._version, payload, customer_id=self._solution["customer_id"] ) - async def update_async( + def update_with_http_info( self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset - ) -> ComplianceInquiriesInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ComplianceInquiriesInstance + Update the ComplianceInquiriesInstance and return response metadata :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. :param theme_set_id: Theme id for styling the inquiry form. - :returns: The updated ComplianceInquiriesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + instance = ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -178,14 +241,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + payload, _, _ = await self._update_async( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) return ComplianceInquiriesInstance( self._version, payload, customer_id=self._solution["customer_id"] ) + async def update_with_http_info_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance and return response metadata + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + instance = ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -209,27 +305,24 @@ def __init__(self, version: Version): self._uri = "/ComplianceInquiries/Customers/Initialize" - def create( + def _create( self, - primary_profile_sid: str, notification_email: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, - ) -> ComplianceInquiriesInstance: + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ComplianceInquiriesInstance - - :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. - :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. - :param theme_set_id: Theme id for styling the inquiry form. + Internal helper for create operation - :returns: The created ComplianceInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "PrimaryProfileSid": primary_profile_sid, "NotificationEmail": notification_email, "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -238,33 +331,73 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ComplianceInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, - primary_profile_sid: str, notification_email: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, ) -> ComplianceInquiriesInstance: """ - Asynchronously create the ComplianceInquiriesInstance + Create the ComplianceInquiriesInstance - :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. :returns: The created ComplianceInquiriesInstance """ + payload, _, _ = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + return ComplianceInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceInquiriesInstance and return response metadata + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { - "PrimaryProfileSid": primary_profile_sid, "NotificationEmail": notification_email, "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -273,12 +406,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Asynchronously create the ComplianceInquiriesInstance + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: The created ComplianceInquiriesInstance + """ + payload, _, _ = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) return ComplianceInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceInquiriesInstance and return response metadata + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, customer_id: str) -> ComplianceInquiriesContext: """ Constructs a ComplianceInquiriesContext diff --git a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py index eccd1ac8cf..5c5a96de06 100644 --- a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( self._solution = { "registration_id": registration_id or self.registration_id, } + self._context: Optional[ComplianceRegistrationInquiriesContext] = None @property @@ -120,6 +122,42 @@ async def update_async( theme_set_id=theme_set_id, ) + def update_with_http_info( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ComplianceRegistrationInquiriesInstance with HTTP info + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + async def update_with_http_info_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance with HTTP info + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -151,18 +189,16 @@ def __init__(self, version: Version, registration_id: str): **self._solution ) - def update( + def _update( self, is_isv_embed: Union[bool, object] = values.unset, theme_set_id: Union[str, object] = values.unset, - ) -> ComplianceRegistrationInquiriesInstance: + ) -> tuple: """ - Update the ComplianceRegistrationInquiriesInstance + Internal helper for update operation - :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. - :param theme_set_id: Theme id for styling the inquiry form. - - :returns: The updated ComplianceRegistrationInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -177,26 +213,61 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + payload, _, _ = self._update( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) return ComplianceRegistrationInquiriesInstance( self._version, payload, registration_id=self._solution["registration_id"] ) - async def update_async( + def update_with_http_info( self, is_isv_embed: Union[bool, object] = values.unset, theme_set_id: Union[str, object] = values.unset, - ) -> ComplianceRegistrationInquiriesInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + Update the ComplianceRegistrationInquiriesInstance and return response metadata :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. :param theme_set_id: Theme id for styling the inquiry form. - :returns: The updated ComplianceRegistrationInquiriesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + instance = ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -211,14 +282,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + payload, _, _ = await self._update_async( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) return ComplianceRegistrationInquiriesInstance( self._version, payload, registration_id=self._solution["registration_id"] ) + async def update_with_http_info_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance and return response metadata + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id + ) + instance = ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,7 +354,7 @@ def __init__(self, version: Version): "/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize" ) - def create( + def _create( self, end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", @@ -292,51 +400,12 @@ def create( isv_registering_for_self_or_tenant: Union[str, object] = values.unset, status_callback_url: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, - ) -> ComplianceRegistrationInquiriesInstance: + ) -> tuple: """ - Create the ComplianceRegistrationInquiriesInstance - - :param end_user_type: - :param phone_number_type: - :param business_identity_type: - :param business_registration_authority: - :param business_legal_name: he name of the business or organization using the Tollfree number. - :param notification_email: he email address to receive the notification about the verification result. - :param accepted_notification_receipt: The email address to receive the notification about the verification result. - :param business_registration_number: Business registration number of the business - :param business_website_url: The URL of the business website - :param friendly_name: Friendly name for your business information - :param authorized_representative1_first_name: First name of the authorized representative - :param authorized_representative1_last_name: Last name of the authorized representative - :param authorized_representative1_phone: Phone number of the authorized representative - :param authorized_representative1_email: Email address of the authorized representative - :param authorized_representative1_date_of_birth: Birthdate of the authorized representative - :param address_street: Street address of the business - :param address_street_secondary: Street address of the business - :param address_city: City of the business - :param address_subdivision: State or province of the business - :param address_postal_code: Postal code of the business - :param address_country_code: Country code of the business - :param emergency_address_street: Street address of the business - :param emergency_address_street_secondary: Street address of the business - :param emergency_address_city: City of the business - :param emergency_address_subdivision: State or province of the business - :param emergency_address_postal_code: Postal code of the business - :param emergency_address_country_code: Country code of the business - :param use_address_as_emergency_address: Use the business address as the emergency address - :param file_name: The name of the verification document to upload - :param file: The verification document to upload - :param first_name: The first name of the Individual User. - :param last_name: The last name of the Individual User. - :param date_of_birth: The date of birth of the Individual User. - :param individual_email: The email address of the Individual User. - :param individual_phone: The phone number of the Individual User. - :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. - :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. - :param status_callback_url: The url we call to inform you of bundle changes. - :param theme_set_id: Theme id for styling the inquiry form. + Internal helper for create operation - :returns: The created ComplianceRegistrationInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -392,13 +461,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ComplianceRegistrationInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", @@ -446,7 +513,7 @@ async def create_async( theme_set_id: Union[str, object] = values.unset, ) -> ComplianceRegistrationInquiriesInstance: """ - Asynchronously create the ComplianceRegistrationInquiriesInstance + Create the ComplianceRegistrationInquiriesInstance :param end_user_type: :param phone_number_type: @@ -490,6 +557,238 @@ async def create_async( :returns: The created ComplianceRegistrationInquiriesInstance """ + payload, _, _ = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceRegistrationInquiriesInstance and return response metadata + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -544,12 +843,281 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + payload, _, _ = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) return ComplianceRegistrationInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance and return response metadata + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: """ Constructs a ComplianceRegistrationInquiriesContext diff --git a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py index 9cf259a318..691594bd4f 100644 --- a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +23,13 @@ class ComplianceTollfreeInquiriesInstance(InstanceResource): + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + NON_PROFIT = "NON_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + GOVERNMENT = "GOVERNMENT" + class OptInType(object): VERBAL = "VERBAL" WEB_FORM = "WEB_FORM" @@ -67,10 +75,11 @@ def __init__(self, version: Version): self._uri = "/ComplianceInquiries/Tollfree/Initialize" - def create( + def _create( self, tollfree_phone_number: str, notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, use_case_categories: Union[List[str], object] = values.unset, @@ -94,41 +103,35 @@ def create( business_contact_phone: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, skip_messaging_use_case: Union[bool, object] = values.unset, - ) -> ComplianceTollfreeInquiriesInstance: + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ComplianceTollfreeInquiriesInstance - - :param tollfree_phone_number: The Tollfree phone number to be verified - :param notification_email: The email address to receive the notification about the verification result. - :param business_name: The name of the business or organization using the Tollfree number. - :param business_website: The website of the business or organization using the Tollfree number. - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. - :param use_case_summary: Use this to further explain how messaging is used by the business or organization. - :param production_message_sample: An example of message content, i.e. a sample message. - :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. - :param opt_in_type: - :param message_volume: Estimate monthly volume of messages from the Tollfree Number. - :param business_street_address: The address of the business or organization using the Tollfree number. - :param business_street_address2: The address of the business or organization using the Tollfree number. - :param business_city: The city of the business or organization using the Tollfree number. - :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. - :param business_postal_code: The postal code of the business or organization using the Tollfree number. - :param business_country: The country of the business or organization using the Tollfree number. - :param additional_information: Additional information to be provided for verification. - :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. - :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. - :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. - :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. - :param theme_set_id: Theme id for styling the inquiry form. - :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + Internal helper for create operation - :returns: The created ComplianceTollfreeInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { "TollfreePhoneNumber": tollfree_phone_number, "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, "BusinessName": business_name, "BusinessWebsite": business_website, "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), @@ -152,6 +155,20 @@ def create( "SkipMessagingUseCase": serialize.boolean_to_string( skip_messaging_use_case ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -160,16 +177,15 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ComplianceTollfreeInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, tollfree_phone_number: str, notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, use_case_categories: Union[List[str], object] = values.unset, @@ -193,12 +209,29 @@ async def create_async( business_contact_phone: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, ) -> ComplianceTollfreeInquiriesInstance: """ - Asynchronously create the ComplianceTollfreeInquiriesInstance + Create the ComplianceTollfreeInquiriesInstance :param tollfree_phone_number: The Tollfree phone number to be verified :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. @@ -220,14 +253,254 @@ async def create_async( :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. :param theme_set_id: Theme id for styling the inquiry form. :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. :returns: The created ComplianceTollfreeInquiriesInstance """ + payload, _, _ = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceTollfreeInquiriesInstance and return response metadata + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { "TollfreePhoneNumber": tollfree_phone_number, "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, "BusinessName": business_name, "BusinessWebsite": business_website, "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), @@ -251,6 +524,20 @@ async def create_async( "SkipMessagingUseCase": serialize.boolean_to_string( skip_messaging_use_case ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -259,12 +546,273 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + payload, _, _ = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) return ComplianceTollfreeInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance and return response metadata + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/trusthub/v1/customer_profiles/__init__.py b/twilio/rest/trusthub/v1/customer_profiles/__init__.py index bf5264e31d..5ba9df5ecb 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/__init__.py +++ b/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesInstance": """ Fetch the CustomerProfilesInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "CustomerProfilesInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -185,6 +223,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomerProfilesInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomerProfilesInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def customer_profiles_channel_endpoint_assignment( self, @@ -247,6 +333,20 @@ def __init__(self, version: Version, sid: str): CustomerProfilesEvaluationsList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesInstance @@ -254,10 +354,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -266,71 +388,121 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CustomerProfilesInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CustomerProfilesInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CustomerProfilesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CustomerProfilesInstance: + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + payload, _, _ = self._fetch() return CustomerProfilesInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CustomerProfilesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CustomerProfilesInstance + Fetch the CustomerProfilesInstance and return response metadata - :returns: The fetched CustomerProfilesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + payload, _, _ = await self._fetch_async() return CustomerProfilesInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> CustomerProfilesInstance: + ) -> tuple: """ - Update the CustomerProfilesInstance - - :param status: - :param status_callback: The URL we call to inform your application of status changes. - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Customer-Profile resource changes status. + Internal helper for update operation - :returns: The updated CustomerProfilesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -347,30 +519,77 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) return CustomerProfilesInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> CustomerProfilesInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the CustomerProfilesInstance + Update the CustomerProfilesInstance and return response metadata :param status: :param status_callback: The URL we call to inform your application of status changes. :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Customer-Profile resource changes status. - :returns: The updated CustomerProfilesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -387,14 +606,65 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) return CustomerProfilesInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomerProfilesInstance and return response metadata + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def customer_profiles_channel_endpoint_assignment( self, @@ -457,6 +727,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CustomerProfilesInstance: :param payload: Payload response from the API """ + return CustomerProfilesInstance(self._version, payload) def __repr__(self) -> str: @@ -481,22 +752,18 @@ def __init__(self, version: Version): self._uri = "/CustomerProfiles" - def create( + def _create( self, friendly_name: str, email: str, policy_sid: str, status_callback: Union[str, object] = values.unset, - ) -> CustomerProfilesInstance: + ) -> tuple: """ - Create the CustomerProfilesInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Customer-Profile resource changes status. - :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. - :param status_callback: The URL we call to inform your application of status changes. - - :returns: The created CustomerProfilesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -513,13 +780,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CustomerProfilesInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -527,7 +792,7 @@ async def create_async( status_callback: Union[str, object] = values.unset, ) -> CustomerProfilesInstance: """ - Asynchronously create the CustomerProfilesInstance + Create the CustomerProfilesInstance :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Customer-Profile resource changes status. @@ -536,6 +801,53 @@ async def create_async( :returns: The created CustomerProfilesInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return CustomerProfilesInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CustomerProfilesInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -551,12 +863,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronously create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) return CustomerProfilesInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -629,6 +990,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesInstance and returns headers from first page + + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesInstance and returns headers from first page + + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -654,6 +1085,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -689,6 +1121,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -700,6 +1133,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesInstance and returns headers from first page + + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesInstance and returns headers from first page + + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -784,6 +1285,94 @@ async def page_async( ) return CustomerProfilesPage(self._version, response) + def page_with_http_info( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CustomerProfilesPage: """ Retrieve a specific page of CustomerProfilesInstance records from the API. diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py index 1adca541a8..f0b451d0fa 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesChannelEndpointAssignmentContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": """ Fetch the CustomerProfilesChannelEndpointAssignmentInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "CustomerProfilesChannelEndpointAssignmentInstanc """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesChannelEndpointAssignmentInstance @@ -150,10 +202,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -162,27 +236,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CustomerProfilesChannelEndpointAssignmentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = self._fetch() return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, @@ -190,22 +280,46 @@ def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + Fetch the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata - :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._fetch_async() return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, @@ -213,6 +327,22 @@ async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, @@ -270,16 +401,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create( - self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> CustomerProfilesChannelEndpointAssignmentInstance: + def _create(self, channel_endpoint_type: str, channel_endpoint_sid: str) -> tuple: """ - Create the CustomerProfilesChannelEndpointAssignmentInstance - - :param channel_endpoint_type: The type of channel endpoint. eg: phone-number - :param channel_endpoint_sid: The SID of an channel endpoint + Internal helper for create operation - :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -294,26 +421,61 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) - async def create_async( + def create_with_http_info( self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> CustomerProfilesChannelEndpointAssignmentInstance: + ) -> ApiResponse: """ - Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance + Create the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata :param channel_endpoint_type: The type of channel endpoint. eg: phone-number :param channel_endpoint_sid: The SID of an channel endpoint - :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -328,16 +490,53 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) + async def create_with_http_info_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -404,6 +603,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -427,6 +690,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -459,6 +723,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -469,6 +734,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -507,7 +834,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return CustomerProfilesChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -548,8 +875,94 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return CustomerProfilesChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesChannelEndpointAssignmentPage, status code, and headers + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesChannelEndpointAssignmentPage, status code, and headers + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page( self, target_url: str @@ -564,7 +977,7 @@ def get_page( """ response = self._version.domain.twilio.request("GET", target_url) return CustomerProfilesChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -580,7 +993,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return CustomerProfilesChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> CustomerProfilesChannelEndpointAssignmentContext: diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py index f8710b9cd8..992ac98822 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesEntityAssignmentsContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesEntityAssignmentsInstance": """ Fetch the CustomerProfilesEntityAssignmentsInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "CustomerProfilesEntityAssignmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesEntityAssignmentsInstance @@ -152,10 +204,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -164,27 +238,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CustomerProfilesEntityAssignmentsInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CustomerProfilesEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = self._fetch() return CustomerProfilesEntityAssignmentsInstance( self._version, payload, @@ -192,22 +282,46 @@ def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + Fetch the CustomerProfilesEntityAssignmentsInstance and return response metadata - :returns: The fetched CustomerProfilesEntityAssignmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = await self._fetch_async() return CustomerProfilesEntityAssignmentsInstance( self._version, payload, @@ -215,6 +329,22 @@ async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -239,6 +369,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEntityAssignmentsInstance( self._version, payload, @@ -274,13 +405,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the CustomerProfilesEntityAssignmentsInstance - - :param object_sid: The SID of an object bag that holds information of the different items. + Internal helper for create operation - :returns: The created CustomerProfilesEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -294,25 +424,47 @@ def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: + """ + Create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = self._create(object_sid=object_sid) return CustomerProfilesEntityAssignmentsInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) - async def create_async( - self, object_sid: str - ) -> CustomerProfilesEntityAssignmentsInstance: + def create_with_http_info(self, object_sid: str) -> ApiResponse: """ - Asynchronously create the CustomerProfilesEntityAssignmentsInstance + Create the CustomerProfilesEntityAssignmentsInstance and return response metadata :param object_sid: The SID of an object bag that holds information of the different items. - :returns: The created CustomerProfilesEntityAssignmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -326,16 +478,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, object_sid: str + ) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronously create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + payload, _, _ = await self._create_async(object_sid=object_sid) return CustomerProfilesEntityAssignmentsInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, object_type: Union[str, object] = values.unset, @@ -392,6 +571,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, object_type: Union[str, object] = values.unset, @@ -413,6 +648,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( object_type=object_type, @@ -442,6 +678,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -451,6 +688,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, object_type: Union[str, object] = values.unset, @@ -486,7 +779,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -524,8 +817,88 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEntityAssignmentsPage, status code, and headers + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEntityAssignmentsPage, status code, and headers + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesEntityAssignmentsPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CustomerProfilesEntityAssignmentsPage: """ @@ -538,7 +911,7 @@ def get_page(self, target_url: str) -> CustomerProfilesEntityAssignmentsPage: """ response = self._version.domain.twilio.request("GET", target_url) return CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -554,7 +927,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> CustomerProfilesEntityAssignmentsContext: diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py index 648467aac6..7094e1c0f9 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesEvaluationsContext] = None @property @@ -101,6 +103,24 @@ async def fetch_async(self) -> "CustomerProfilesEvaluationsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,20 +154,30 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): **self._solution ) - def fetch(self) -> CustomerProfilesEvaluationsInstance: + def _fetch(self) -> tuple: """ - Fetch the CustomerProfilesEvaluationsInstance - + Internal helper for fetch operation - :returns: The fetched CustomerProfilesEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEvaluationsInstance: + """ + Fetch the CustomerProfilesEvaluationsInstance + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + payload, _, _ = self._fetch() return CustomerProfilesEvaluationsInstance( self._version, payload, @@ -155,22 +185,46 @@ def fetch(self) -> CustomerProfilesEvaluationsInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + Fetch the CustomerProfilesEvaluationsInstance and return response metadata - :returns: The fetched CustomerProfilesEvaluationsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + payload, _, _ = await self._fetch_async() return CustomerProfilesEvaluationsInstance( self._version, payload, @@ -178,6 +232,22 @@ async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -200,6 +270,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEvaluationsInstance( self._version, payload, @@ -235,13 +306,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: + def _create(self, policy_sid: str) -> tuple: """ - Create the CustomerProfilesEvaluationsInstance - - :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + Internal helper for create operation - :returns: The created CustomerProfilesEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -255,25 +325,47 @@ def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: + """ + Create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + payload, _, _ = self._create(policy_sid=policy_sid) return CustomerProfilesEvaluationsInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) - async def create_async( - self, policy_sid: str - ) -> CustomerProfilesEvaluationsInstance: + def create_with_http_info(self, policy_sid: str) -> ApiResponse: """ - Asynchronously create the CustomerProfilesEvaluationsInstance + Create the CustomerProfilesEvaluationsInstance and return response metadata :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. - :returns: The created CustomerProfilesEvaluationsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(policy_sid=policy_sid) + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, policy_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -287,16 +379,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, policy_sid: str + ) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronously create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + payload, _, _ = await self._create_async(policy_sid=policy_sid) return CustomerProfilesEvaluationsInstance( self._version, payload, customer_profile_sid=self._solution["customer_profile_sid"], ) + async def create_with_http_info_async(self, policy_sid: str) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(policy_sid=policy_sid) + instance = CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -347,6 +466,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -366,6 +535,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -392,6 +562,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -400,6 +571,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -431,7 +652,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + return CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -464,7 +687,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + return CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CustomerProfilesEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> CustomerProfilesEvaluationsPage: """ @@ -476,7 +775,9 @@ def get_page(self, target_url: str) -> CustomerProfilesEvaluationsPage: :returns: Page of CustomerProfilesEvaluationsInstance """ response = self._version.domain.twilio.request("GET", target_url) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + return CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> CustomerProfilesEvaluationsPage: """ @@ -488,7 +789,9 @@ async def get_page_async(self, target_url: str) -> CustomerProfilesEvaluationsPa :returns: Page of CustomerProfilesEvaluationsInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + return CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> CustomerProfilesEvaluationsContext: """ diff --git a/twilio/rest/trusthub/v1/customer_profiles_provisional_copy.py b/twilio/rest/trusthub/v1/customer_profiles_provisional_copy.py new file mode 100644 index 0000000000..65c0823003 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles_provisional_copy.py @@ -0,0 +1,423 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class CustomerProfilesProvisionalCopyInstance(InstanceResource): + """ + :ivar customer_profile_sid: The unique SID identifier of the Customer Profile. + :ivar account_sid: The unique SID identifier of the Account. + :ivar policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar status: The verification status of the Customer-Profile resource. + :ivar email: The email address that will receive updates when the Customer-Profile resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar date_created: The date that this Customer Profiles Provisional Copy was created, given in ISO 8601 format. + :ivar date_updated: The date that this Customer Profiles Provisional Copy was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: Optional[str] = None, + ): + super().__init__(version) + + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid or self.customer_profile_sid, + } + + self._context: Optional[CustomerProfilesProvisionalCopyContext] = None + + @property + def _proxy(self) -> "CustomerProfilesProvisionalCopyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesProvisionalCopyContext for this CustomerProfilesProvisionalCopyInstance + """ + if self._context is None: + self._context = CustomerProfilesProvisionalCopyContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return self._context + + def create(self) -> "CustomerProfilesProvisionalCopyInstance": + """ + Create the CustomerProfilesProvisionalCopyInstance + + + :returns: The created CustomerProfilesProvisionalCopyInstance + """ + return self._proxy.create() + + async def create_async(self) -> "CustomerProfilesProvisionalCopyInstance": + """ + Asynchronous coroutine to create the CustomerProfilesProvisionalCopyInstance + + + :returns: The created CustomerProfilesProvisionalCopyInstance + """ + return await self._proxy.create_async() + + def create_with_http_info(self) -> ApiResponse: + """ + Create the CustomerProfilesProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the CustomerProfilesProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + + def fetch(self) -> "CustomerProfilesProvisionalCopyInstance": + """ + Fetch the CustomerProfilesProvisionalCopyInstance + + + :returns: The fetched CustomerProfilesProvisionalCopyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesProvisionalCopyInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesProvisionalCopyInstance + + + :returns: The fetched CustomerProfilesProvisionalCopyInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesProvisionalCopyInstance {}>".format( + context + ) + + +class CustomerProfilesProvisionalCopyContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesProvisionalCopyContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique SID identifier of the Customer Profile. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/ProvisionalCopy".format( + **self._solution + ) + + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> CustomerProfilesProvisionalCopyInstance: + """ + Create the CustomerProfilesProvisionalCopyInstance + + + :returns: The created CustomerProfilesProvisionalCopyInstance + """ + payload, _, _ = self._create() + return CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the CustomerProfilesProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> CustomerProfilesProvisionalCopyInstance: + """ + Asynchronous coroutine to create the CustomerProfilesProvisionalCopyInstance + + + :returns: The created CustomerProfilesProvisionalCopyInstance + """ + payload, _, _ = await self._create_async() + return CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the CustomerProfilesProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesProvisionalCopyInstance: + """ + Fetch the CustomerProfilesProvisionalCopyInstance + + + :returns: The fetched CustomerProfilesProvisionalCopyInstance + """ + payload, _, _ = self._fetch() + return CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> CustomerProfilesProvisionalCopyInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesProvisionalCopyInstance + + + :returns: The fetched CustomerProfilesProvisionalCopyInstance + """ + payload, _, _ = await self._fetch_async() + return CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CustomerProfilesProvisionalCopyInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesProvisionalCopyContext {}>".format( + context + ) + + +class CustomerProfilesProvisionalCopyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomerProfilesProvisionalCopyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, customer_profile_sid: str) -> CustomerProfilesProvisionalCopyContext: + """ + Constructs a CustomerProfilesProvisionalCopyContext + + :param customer_profile_sid: The unique SID identifier of the Customer Profile. + """ + return CustomerProfilesProvisionalCopyContext( + self._version, customer_profile_sid=customer_profile_sid + ) + + def __call__( + self, customer_profile_sid: str + ) -> CustomerProfilesProvisionalCopyContext: + """ + Constructs a CustomerProfilesProvisionalCopyContext + + :param customer_profile_sid: The unique SID identifier of the Customer Profile. + """ + return CustomerProfilesProvisionalCopyContext( + self._version, customer_profile_sid=customer_profile_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesProvisionalCopyList>" diff --git a/twilio/rest/trusthub/v1/end_user.py b/twilio/rest/trusthub/v1/end_user.py index 5ce3b819d9..bb7c7740b8 100644 --- a/twilio/rest/trusthub/v1/end_user.py +++ b/twilio/rest/trusthub/v1/end_user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EndUserInstance": """ Fetch the EndUserInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "EndUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -144,6 +182,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +245,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/EndUsers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EndUserInstance @@ -178,10 +266,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -190,67 +300,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> EndUserInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the EndUserInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + :returns: The fetched EndUserInstance + """ + payload, _, _ = self._fetch() return EndUserInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EndUserInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EndUserInstance + Fetch the EndUserInstance and return response metadata - :returns: The fetched EndUserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + payload, _, _ = await self._fetch_async() return EndUserInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Update the EndUserInstance - - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + Internal helper for update operation - :returns: The updated EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -265,25 +427,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronous coroutine to update the EndUserInstance + Update the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. :returns: The updated EndUserInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -297,12 +490,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = EndUserInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -321,6 +549,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -345,20 +574,17 @@ def __init__(self, version: Version): self._uri = "/EndUsers" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Create the EndUserInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param type: The type of end user of the Bundle resource - can be `individual` or `business`. - :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. - - :returns: The created EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -374,20 +600,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return EndUserInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronously create the EndUserInstance + Create the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of end user of the Bundle resource - can be `individual` or `business`. @@ -395,6 +619,44 @@ async def create_async( :returns: The created EndUserInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -409,12 +671,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return EndUserInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -465,6 +766,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -484,6 +835,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -510,6 +862,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -518,6 +871,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -584,6 +987,76 @@ async def page_async( ) return EndUserPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EndUserPage: """ Retrieve a specific page of EndUserInstance records from the API. diff --git a/twilio/rest/trusthub/v1/end_user_type.py b/twilio/rest/trusthub/v1/end_user_type.py index 0eb2957e0a..8f2da577fb 100644 --- a/twilio/rest/trusthub/v1/end_user_type.py +++ b/twilio/rest/trusthub/v1/end_user_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "EndUserTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,48 +126,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/EndUserTypes/{sid}".format(**self._solution) - def fetch(self) -> EndUserTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the EndUserTypeInstance - + Internal helper for fetch operation - :returns: The fetched EndUserTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = self._fetch() return EndUserTypeInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> EndUserTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EndUserTypeInstance + Fetch the EndUserTypeInstance and return response metadata - :returns: The fetched EndUserTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + payload, _, _ = await self._fetch_async() return EndUserTypeInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -240,6 +309,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -259,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -285,6 +405,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -293,6 +414,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EndUserTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -359,6 +530,76 @@ async def page_async( ) return EndUserTypePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EndUserTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EndUserTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> EndUserTypePage: """ Retrieve a specific page of EndUserTypeInstance records from the API. diff --git a/twilio/rest/trusthub/v1/policies.py b/twilio/rest/trusthub/v1/policies.py index 36a0916c51..ed7035da27 100644 --- a/twilio/rest/trusthub/v1/policies.py +++ b/twilio/rest/trusthub/v1/policies.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PoliciesContext] = None @property @@ -77,6 +79,24 @@ async def fetch_async(self) -> "PoliciesInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -104,48 +124,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Policies/{sid}".format(**self._solution) - def fetch(self) -> PoliciesInstance: + def _fetch(self) -> tuple: """ - Fetch the PoliciesInstance - + Internal helper for fetch operation - :returns: The fetched PoliciesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> PoliciesInstance: + """ + Fetch the PoliciesInstance + + :returns: The fetched PoliciesInstance + """ + payload, _, _ = self._fetch() return PoliciesInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> PoliciesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PoliciesInstance + Fetch the PoliciesInstance and return response metadata - :returns: The fetched PoliciesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PoliciesInstance: + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + payload, _, _ = await self._fetch_async() return PoliciesInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PoliciesInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,6 +232,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PoliciesInstance: :param payload: Payload response from the API """ + return PoliciesInstance(self._version, payload) def __repr__(self) -> str: @@ -238,6 +307,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -257,6 +376,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -283,6 +403,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -291,6 +412,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PoliciesInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -357,6 +528,76 @@ async def page_async( ) return PoliciesPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PoliciesPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PoliciesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PoliciesPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PoliciesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> PoliciesPage: """ Retrieve a specific page of PoliciesInstance records from the API. diff --git a/twilio/rest/trusthub/v1/supporting_document.py b/twilio/rest/trusthub/v1/supporting_document.py index b53d7d319c..8020232292 100644 --- a/twilio/rest/trusthub/v1/supporting_document.py +++ b/twilio/rest/trusthub/v1/supporting_document.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,12 +26,12 @@ class SupportingDocumentInstance(InstanceResource): class Status(object): - DRAFT = "draft" - PENDING_REVIEW = "pending-review" - REJECTED = "rejected" - APPROVED = "approved" - EXPIRED = "expired" - PROVISIONALLY_APPROVED = "provisionally-approved" + DRAFT = "DRAFT" + PENDING_REVIEW = "PENDING_REVIEW" + REJECTED = "REJECTED" + APPROVED = "APPROVED" + EXPIRED = "EXPIRED" + PROVISIONALLY_APPROVED = "PROVISIONALLY_APPROVED" """ :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SupportingDocumentInstance": """ Fetch the SupportingDocumentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "SupportingDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -159,6 +197,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -186,6 +260,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SupportingDocuments/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SupportingDocumentInstance @@ -193,10 +281,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -205,67 +315,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SupportingDocumentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SupportingDocumentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = self._fetch() return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SupportingDocumentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SupportingDocumentInstance + Fetch the SupportingDocumentInstance and return response metadata - :returns: The fetched SupportingDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + payload, _, _ = await self._fetch_async() return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Update the SupportingDocumentInstance + Internal helper for update operation - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. - - :returns: The updated SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -280,26 +442,59 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SupportingDocumentInstance + Update the SupportingDocumentInstance and return response metadata :param friendly_name: The string that you assigned to describe the resource. :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. - :returns: The updated SupportingDocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -314,14 +509,51 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) return SupportingDocumentInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, attributes=attributes + ) + instance = SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -340,6 +572,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -364,20 +597,17 @@ def __init__(self, version: Version): self._uri = "/SupportingDocuments" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Create the SupportingDocumentInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param type: The type of the Supporting Document. - :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. - - :returns: The created SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,20 +623,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SupportingDocumentInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> SupportingDocumentInstance: """ - Asynchronously create the SupportingDocumentInstance + Create the SupportingDocumentInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of the Supporting Document. @@ -414,6 +642,44 @@ async def create_async( :returns: The created SupportingDocumentInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -428,12 +694,51 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return SupportingDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -484,6 +789,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -503,6 +858,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -529,6 +885,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -537,6 +894,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -603,6 +1010,76 @@ async def page_async( ) return SupportingDocumentPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SupportingDocumentPage: """ Retrieve a specific page of SupportingDocumentInstance records from the API. diff --git a/twilio/rest/trusthub/v1/supporting_document_type.py b/twilio/rest/trusthub/v1/supporting_document_type.py index f107397a4c..2ae6cb345e 100644 --- a/twilio/rest/trusthub/v1/supporting_document_type.py +++ b/twilio/rest/trusthub/v1/supporting_document_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "SupportingDocumentTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,48 +126,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SupportingDocumentTypes/{sid}".format(**self._solution) - def fetch(self) -> SupportingDocumentTypeInstance: + def _fetch(self) -> tuple: """ - Fetch the SupportingDocumentTypeInstance - + Internal helper for fetch operation - :returns: The fetched SupportingDocumentTypeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = self._fetch() return SupportingDocumentTypeInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SupportingDocumentTypeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + Fetch the SupportingDocumentTypeInstance and return response metadata - :returns: The fetched SupportingDocumentTypeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + payload, _, _ = await self._fetch_async() return SupportingDocumentTypeInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstanc :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -240,6 +309,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -259,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -285,6 +405,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -293,6 +414,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SupportingDocumentTypeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -359,6 +530,76 @@ async def page_async( ) return SupportingDocumentTypePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SupportingDocumentTypePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SupportingDocumentTypePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SupportingDocumentTypePage: """ Retrieve a specific page of SupportingDocumentTypeInstance records from the API. diff --git a/twilio/rest/trusthub/v1/trust_products/__init__.py b/twilio/rest/trusthub/v1/trust_products/__init__.py index 6bb01d61dc..3c2553dbbe 100644 --- a/twilio/rest/trusthub/v1/trust_products/__init__.py +++ b/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[TrustProductsContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsInstance": """ Fetch the TrustProductsInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "TrustProductsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["TrustProductsInstance.Status", object] = values.unset, @@ -185,6 +223,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrustProductsInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrustProductsInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def trust_products_channel_endpoint_assignment( self, @@ -243,6 +329,20 @@ def __init__(self, version: Version, sid: str): ] = None self._trust_products_evaluations: Optional[TrustProductsEvaluationsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsInstance @@ -250,10 +350,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -262,71 +384,121 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TrustProductsInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TrustProductsInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TrustProductsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> TrustProductsInstance: + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + payload, _, _ = self._fetch() return TrustProductsInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> TrustProductsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrustProductsInstance + Fetch the TrustProductsInstance and return response metadata - :returns: The fetched TrustProductsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrustProductsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + payload, _, _ = await self._fetch_async() return TrustProductsInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, status: Union["TrustProductsInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> TrustProductsInstance: + ) -> tuple: """ - Update the TrustProductsInstance - - :param status: - :param status_callback: The URL we call to inform your application of status changes. - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Trust Product resource changes status. + Internal helper for update operation - :returns: The updated TrustProductsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -343,13 +515,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, status: Union["TrustProductsInstance.Status", object] = values.unset, status_callback: Union[str, object] = values.unset, @@ -357,7 +527,7 @@ async def update_async( email: Union[str, object] = values.unset, ) -> TrustProductsInstance: """ - Asynchronous coroutine to update the TrustProductsInstance + Update the TrustProductsInstance :param status: :param status_callback: The URL we call to inform your application of status changes. @@ -366,6 +536,55 @@ async def update_async( :returns: The updated TrustProductsInstance """ + payload, _, _ = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrustProductsInstance and return response metadata + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = TrustProductsInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -381,12 +600,63 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronous coroutine to update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrustProductsInstance and return response metadata + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + instance = TrustProductsInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def trust_products_channel_endpoint_assignment( self, @@ -447,6 +717,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrustProductsInstance: :param payload: Payload response from the API """ + return TrustProductsInstance(self._version, payload) def __repr__(self) -> str: @@ -471,22 +742,18 @@ def __init__(self, version: Version): self._uri = "/TrustProducts" - def create( + def _create( self, friendly_name: str, email: str, policy_sid: str, status_callback: Union[str, object] = values.unset, - ) -> TrustProductsInstance: + ) -> tuple: """ - Create the TrustProductsInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the resource. - :param email: The email address that will receive updates when the Trust Product resource changes status. - :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. - :param status_callback: The URL we call to inform your application of status changes. - - :returns: The created TrustProductsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -503,13 +770,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TrustProductsInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -517,7 +782,7 @@ async def create_async( status_callback: Union[str, object] = values.unset, ) -> TrustProductsInstance: """ - Asynchronously create the TrustProductsInstance + Create the TrustProductsInstance :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Trust Product resource changes status. @@ -526,6 +791,53 @@ async def create_async( :returns: The created TrustProductsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return TrustProductsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TrustProductsInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = TrustProductsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -541,12 +853,61 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronously create the TrustProductsInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created TrustProductsInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) return TrustProductsInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TrustProductsInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = TrustProductsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["TrustProductsInstance.Status", object] = values.unset, @@ -619,6 +980,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsInstance and returns headers from first page + + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsInstance and returns headers from first page + + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["TrustProductsInstance.Status", object] = values.unset, @@ -644,6 +1075,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -679,6 +1111,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -690,6 +1123,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsInstance and returns headers from first page + + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsInstance and returns headers from first page + + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["TrustProductsInstance.Status", object] = values.unset, @@ -774,6 +1275,94 @@ async def page_async( ) return TrustProductsPage(self._version, response) + def page_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TrustProductsPage: """ Retrieve a specific page of TrustProductsInstance records from the API. diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py index adf9c51f51..0f16a1a57c 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsChannelEndpointAssignmentContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsChannelEndpointAssignmentInstance": """ Fetch the TrustProductsChannelEndpointAssignmentInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "TrustProductsChannelEndpointAssignmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsChannelEndpointAssignmentInstance @@ -150,10 +202,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -162,27 +236,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TrustProductsChannelEndpointAssignmentInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = self._fetch() return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, @@ -190,22 +280,46 @@ def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + Fetch the TrustProductsChannelEndpointAssignmentInstance and return response metadata - :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._fetch_async() return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, @@ -213,6 +327,22 @@ async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, @@ -272,16 +403,12 @@ def __init__(self, version: Version, trust_product_sid: str): ) ) - def create( - self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> TrustProductsChannelEndpointAssignmentInstance: + def _create(self, channel_endpoint_type: str, channel_endpoint_sid: str) -> tuple: """ - Create the TrustProductsChannelEndpointAssignmentInstance - - :param channel_endpoint_type: The type of channel endpoint. eg: phone-number - :param channel_endpoint_sid: The SID of an channel endpoint + Internal helper for create operation - :returns: The created TrustProductsChannelEndpointAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -296,26 +423,61 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) - async def create_async( + def create_with_http_info( self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> TrustProductsChannelEndpointAssignmentInstance: + ) -> ApiResponse: """ - Asynchronously create the TrustProductsChannelEndpointAssignmentInstance + Create the TrustProductsChannelEndpointAssignmentInstance and return response metadata :param channel_endpoint_type: The type of channel endpoint. eg: phone-number :param channel_endpoint_sid: The SID of an channel endpoint - :returns: The created TrustProductsChannelEndpointAssignmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -330,16 +492,53 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronously create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + payload, _, _ = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) + async def create_with_http_info_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> ApiResponse: + """ + Asynchronously create the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + channel_endpoint_type=channel_endpoint_type, + channel_endpoint_sid=channel_endpoint_sid, + ) + instance = TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -406,6 +605,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -429,6 +692,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -461,6 +725,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -471,6 +736,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsChannelEndpointAssignmentInstance and returns headers from first page + + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, channel_endpoint_sid: Union[str, object] = values.unset, @@ -509,7 +836,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return TrustProductsChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -550,8 +877,94 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return TrustProductsChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsChannelEndpointAssignmentPage, status code, and headers + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsChannelEndpointAssignmentPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsChannelEndpointAssignmentPage, status code, and headers + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsChannelEndpointAssignmentPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TrustProductsChannelEndpointAssignmentPage: """ @@ -564,7 +977,7 @@ def get_page(self, target_url: str) -> TrustProductsChannelEndpointAssignmentPag """ response = self._version.domain.twilio.request("GET", target_url) return TrustProductsChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -580,7 +993,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return TrustProductsChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> TrustProductsChannelEndpointAssignmentContext: diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py index ebda7ee8c0..f4525abc80 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsEntityAssignmentsContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsEntityAssignmentsInstance": """ Fetch the TrustProductsEntityAssignmentsInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "TrustProductsEntityAssignmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsEntityAssignmentsInstance @@ -148,10 +200,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -160,27 +234,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> TrustProductsEntityAssignmentsInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the TrustProductsEntityAssignmentsInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched TrustProductsEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEntityAssignmentsInstance: + """ + Fetch the TrustProductsEntityAssignmentsInstance + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = self._fetch() return TrustProductsEntityAssignmentsInstance( self._version, payload, @@ -188,22 +278,46 @@ def fetch(self) -> TrustProductsEntityAssignmentsInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + Fetch the TrustProductsEntityAssignmentsInstance and return response metadata - :returns: The fetched TrustProductsEntityAssignmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = await self._fetch_async() return TrustProductsEntityAssignmentsInstance( self._version, payload, @@ -211,6 +325,22 @@ async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -233,6 +363,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsEntityAssignmentsInstance( self._version, payload, @@ -268,13 +399,12 @@ def __init__(self, version: Version, trust_product_sid: str): **self._solution ) - def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the TrustProductsEntityAssignmentsInstance - - :param object_sid: The SID of an object bag that holds information of the different items. + Internal helper for create operation - :returns: The created TrustProductsEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -288,25 +418,47 @@ def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: + """ + Create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = self._create(object_sid=object_sid) return TrustProductsEntityAssignmentsInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) - async def create_async( - self, object_sid: str - ) -> TrustProductsEntityAssignmentsInstance: + def create_with_http_info(self, object_sid: str) -> ApiResponse: """ - Asynchronously create the TrustProductsEntityAssignmentsInstance + Create the TrustProductsEntityAssignmentsInstance and return response metadata :param object_sid: The SID of an object bag that holds information of the different items. - :returns: The created TrustProductsEntityAssignmentsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(object_sid=object_sid) + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, object_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -320,16 +472,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, object_sid: str + ) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronously create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + payload, _, _ = await self._create_async(object_sid=object_sid) return TrustProductsEntityAssignmentsInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) + async def create_with_http_info_async(self, object_sid: str) -> ApiResponse: + """ + Asynchronously create the TrustProductsEntityAssignmentsInstance and return response metadata + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(object_sid=object_sid) + instance = TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, object_type: Union[str, object] = values.unset, @@ -386,6 +565,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, object_type: Union[str, object] = values.unset, @@ -407,6 +642,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( object_type=object_type, @@ -436,6 +672,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +682,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, object_type: Union[str, object] = values.unset, @@ -480,7 +773,7 @@ def page( method="GET", uri=self._uri, params=data, headers=headers ) return TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -518,8 +811,88 @@ async def page_async( method="GET", uri=self._uri, params=data, headers=headers ) return TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEntityAssignmentsPage, status code, and headers + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsEntityAssignmentsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEntityAssignmentsPage, status code, and headers + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsEntityAssignmentsPage( + self._version, response, solution=self._solution ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TrustProductsEntityAssignmentsPage: """ @@ -532,7 +905,7 @@ def get_page(self, target_url: str) -> TrustProductsEntityAssignmentsPage: """ response = self._version.domain.twilio.request("GET", target_url) return TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def get_page_async( @@ -548,7 +921,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> TrustProductsEntityAssignmentsContext: diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py index 3691aa017b..f27af2615f 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsEvaluationsContext] = None @property @@ -101,6 +103,24 @@ async def fetch_async(self) -> "TrustProductsEvaluationsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,20 +154,30 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **self._solution ) - def fetch(self) -> TrustProductsEvaluationsInstance: + def _fetch(self) -> tuple: """ - Fetch the TrustProductsEvaluationsInstance - + Internal helper for fetch operation - :returns: The fetched TrustProductsEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEvaluationsInstance: + """ + Fetch the TrustProductsEvaluationsInstance + + :returns: The fetched TrustProductsEvaluationsInstance + """ + payload, _, _ = self._fetch() return TrustProductsEvaluationsInstance( self._version, payload, @@ -155,22 +185,46 @@ def fetch(self) -> TrustProductsEvaluationsInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> TrustProductsEvaluationsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + Fetch the TrustProductsEvaluationsInstance and return response metadata - :returns: The fetched TrustProductsEvaluationsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> TrustProductsEvaluationsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + payload, _, _ = await self._fetch_async() return TrustProductsEvaluationsInstance( self._version, payload, @@ -178,6 +232,22 @@ async def fetch_async(self) -> TrustProductsEvaluationsInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -196,6 +266,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrustProductsEvaluationsInsta :param payload: Payload response from the API """ + return TrustProductsEvaluationsInstance( self._version, payload, @@ -231,13 +302,12 @@ def __init__(self, version: Version, trust_product_sid: str): **self._solution ) - def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + def _create(self, policy_sid: str) -> tuple: """ - Create the TrustProductsEvaluationsInstance + Internal helper for create operation - :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. - - :returns: The created TrustProductsEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -251,23 +321,47 @@ def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + payload, _, _ = self._create(policy_sid=policy_sid) return TrustProductsEvaluationsInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) - async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + def create_with_http_info(self, policy_sid: str) -> ApiResponse: """ - Asynchronously create the TrustProductsEvaluationsInstance + Create the TrustProductsEvaluationsInstance and return response metadata :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. - :returns: The created TrustProductsEvaluationsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(policy_sid=policy_sid) + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, policy_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,16 +375,41 @@ async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstanc headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Asynchronously create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + payload, _, _ = await self._create_async(policy_sid=policy_sid) return TrustProductsEvaluationsInstance( self._version, payload, trust_product_sid=self._solution["trust_product_sid"], ) + async def create_with_http_info_async(self, policy_sid: str) -> ApiResponse: + """ + Asynchronously create the TrustProductsEvaluationsInstance and return response metadata + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(policy_sid=policy_sid) + instance = TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -341,6 +460,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -360,6 +529,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -386,6 +556,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -394,6 +565,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsEvaluationsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -425,7 +646,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + return TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -458,7 +681,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + return TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TrustProductsEvaluationsPage: """ @@ -470,7 +769,9 @@ def get_page(self, target_url: str) -> TrustProductsEvaluationsPage: :returns: Page of TrustProductsEvaluationsInstance """ response = self._version.domain.twilio.request("GET", target_url) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + return TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> TrustProductsEvaluationsPage: """ @@ -482,7 +783,9 @@ async def get_page_async(self, target_url: str) -> TrustProductsEvaluationsPage: :returns: Page of TrustProductsEvaluationsInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + return TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> TrustProductsEvaluationsContext: """ diff --git a/twilio/rest/trusthub/v1/trust_products_provisional_copy.py b/twilio/rest/trusthub/v1/trust_products_provisional_copy.py new file mode 100644 index 0000000000..249e489e0c --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products_provisional_copy.py @@ -0,0 +1,421 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TrustProductsProvisionalCopyInstance(InstanceResource): + """ + :ivar trust_product_sid: The unique SID identifier of the Trust Product. + :ivar account_sid: The unique SID identifier of the Account. + :ivar policy_sid: The unique SID identifier of the Policy. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar status: The verification status of the Customer-Profile resource. + :ivar email: The email address that will receive updates when the trust product resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar date_created: The date that this Trust Products Provisional Copy was created, given in ISO 8601 format. + :ivar date_updated: The date that this Trust Products Provisional Copy was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: Optional[str] = None, + ): + super().__init__(version) + + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid or self.trust_product_sid, + } + + self._context: Optional[TrustProductsProvisionalCopyContext] = None + + @property + def _proxy(self) -> "TrustProductsProvisionalCopyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsProvisionalCopyContext for this TrustProductsProvisionalCopyInstance + """ + if self._context is None: + self._context = TrustProductsProvisionalCopyContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + ) + return self._context + + def create(self) -> "TrustProductsProvisionalCopyInstance": + """ + Create the TrustProductsProvisionalCopyInstance + + + :returns: The created TrustProductsProvisionalCopyInstance + """ + return self._proxy.create() + + async def create_async(self) -> "TrustProductsProvisionalCopyInstance": + """ + Asynchronous coroutine to create the TrustProductsProvisionalCopyInstance + + + :returns: The created TrustProductsProvisionalCopyInstance + """ + return await self._proxy.create_async() + + def create_with_http_info(self) -> ApiResponse: + """ + Create the TrustProductsProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the TrustProductsProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + + def fetch(self) -> "TrustProductsProvisionalCopyInstance": + """ + Fetch the TrustProductsProvisionalCopyInstance + + + :returns: The fetched TrustProductsProvisionalCopyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsProvisionalCopyInstance": + """ + Asynchronous coroutine to fetch the TrustProductsProvisionalCopyInstance + + + :returns: The fetched TrustProductsProvisionalCopyInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsProvisionalCopyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsProvisionalCopyInstance {}>".format( + context + ) + + +class TrustProductsProvisionalCopyContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsProvisionalCopyContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique SID identifier of the Trust Product. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/ProvisionalCopy".format( + **self._solution + ) + + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> TrustProductsProvisionalCopyInstance: + """ + Create the TrustProductsProvisionalCopyInstance + + + :returns: The created TrustProductsProvisionalCopyInstance + """ + payload, _, _ = self._create() + return TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the TrustProductsProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> TrustProductsProvisionalCopyInstance: + """ + Asynchronous coroutine to create the TrustProductsProvisionalCopyInstance + + + :returns: The created TrustProductsProvisionalCopyInstance + """ + payload, _, _ = await self._create_async() + return TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the TrustProductsProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsProvisionalCopyInstance: + """ + Fetch the TrustProductsProvisionalCopyInstance + + + :returns: The fetched TrustProductsProvisionalCopyInstance + """ + payload, _, _ = self._fetch() + return TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TrustProductsProvisionalCopyInstance: + """ + Asynchronous coroutine to fetch the TrustProductsProvisionalCopyInstance + + + :returns: The fetched TrustProductsProvisionalCopyInstance + """ + payload, _, _ = await self._fetch_async() + return TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsProvisionalCopyInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TrustProductsProvisionalCopyInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsProvisionalCopyContext {}>".format( + context + ) + + +class TrustProductsProvisionalCopyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrustProductsProvisionalCopyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, trust_product_sid: str) -> TrustProductsProvisionalCopyContext: + """ + Constructs a TrustProductsProvisionalCopyContext + + :param trust_product_sid: The unique SID identifier of the Trust Product. + """ + return TrustProductsProvisionalCopyContext( + self._version, trust_product_sid=trust_product_sid + ) + + def __call__(self, trust_product_sid: str) -> TrustProductsProvisionalCopyContext: + """ + Constructs a TrustProductsProvisionalCopyContext + + :param trust_product_sid: The unique SID identifier of the Trust Product. + """ + return TrustProductsProvisionalCopyContext( + self._version, trust_product_sid=trust_product_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsProvisionalCopyList>" diff --git a/twilio/rest/verify/v2/form.py b/twilio/rest/verify/v2/form.py index 454030208d..223f6b6d15 100644 --- a/twilio/rest/verify/v2/form.py +++ b/twilio/rest/verify/v2/form.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ def __init__( self._solution = { "form_type": form_type or self.form_type, } + self._context: Optional[FormContext] = None @property @@ -83,6 +85,24 @@ async def fetch_async(self) -> "FormInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FormInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FormInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -110,48 +130,96 @@ def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): } self._uri = "/Forms/{form_type}".format(**self._solution) - def fetch(self) -> FormInstance: + def _fetch(self) -> tuple: """ - Fetch the FormInstance + Internal helper for fetch operation - - :returns: The fetched FormInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> FormInstance: + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + payload, _, _ = self._fetch() return FormInstance( self._version, payload, form_type=self._solution["form_type"], ) - async def fetch_async(self) -> FormInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FormInstance + Fetch the FormInstance and return response metadata - :returns: The fetched FormInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FormInstance: + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + payload, _, _ = await self._fetch_async() return FormInstance( self._version, payload, form_type=self._solution["form_type"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FormInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/verify/v2/safelist.py b/twilio/rest/verify/v2/safelist.py index 00fc0976f7..9ea8069e48 100644 --- a/twilio/rest/verify/v2/safelist.py +++ b/twilio/rest/verify/v2/safelist.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[SafelistContext] = None @property @@ -77,6 +79,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SafelistInstance": """ Fetch the SafelistInstance @@ -95,6 +115,24 @@ async def fetch_async(self) -> "SafelistInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -122,6 +160,20 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/SafeList/Numbers/{phone_number}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SafelistInstance @@ -129,10 +181,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SafelistInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -141,55 +215,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SafelistInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SafelistInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SafelistInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SafelistInstance: + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + payload, _, _ = self._fetch() return SafelistInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async(self) -> SafelistInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SafelistInstance + Fetch the SafelistInstance and return response metadata - :returns: The fetched SafelistInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SafelistInstance: + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + payload, _, _ = await self._fetch_async() return SafelistInstance( self._version, payload, phone_number=self._solution["phone_number"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SafelistInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -213,13 +341,12 @@ def __init__(self, version: Version): self._uri = "/SafeList/Numbers" - def create(self, phone_number: str) -> SafelistInstance: + def _create(self, phone_number: str) -> tuple: """ - Create the SafelistInstance + Internal helper for create operation - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - - :returns: The created SafelistInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -233,19 +360,39 @@ def create(self, phone_number: str) -> SafelistInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + payload, _, _ = self._create(phone_number=phone_number) return SafelistInstance(self._version, payload) - async def create_async(self, phone_number: str) -> SafelistInstance: + def create_with_http_info(self, phone_number: str) -> ApiResponse: """ - Asynchronously create the SafelistInstance + Create the SafelistInstance and return response metadata :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :returns: The created SafelistInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -259,12 +406,35 @@ async def create_async(self, phone_number: str) -> SafelistInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + payload, _, _ = await self._create_async(phone_number=phone_number) return SafelistInstance(self._version, payload) + async def create_with_http_info_async(self, phone_number: str) -> ApiResponse: + """ + Asynchronously create the SafelistInstance and return response metadata + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number + ) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, phone_number: str) -> SafelistContext: """ Constructs a SafelistContext diff --git a/twilio/rest/verify/v2/service/__init__.py b/twilio/rest/verify/v2/service/__init__.py index 207e8e7b53..ed9b7747be 100644 --- a/twilio/rest/verify/v2/service/__init__.py +++ b/twilio/rest/verify/v2/service/__init__.py @@ -15,16 +15,21 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.verify.v2.service.access_token import AccessTokenList +from twilio.rest.verify.v2.service.approve_challenge import ApproveChallengeList from twilio.rest.verify.v2.service.entity import EntityList from twilio.rest.verify.v2.service.messaging_configuration import ( MessagingConfigurationList, ) +from twilio.rest.verify.v2.service.new_challenge import NewChallengeList +from twilio.rest.verify.v2.service.new_factor import NewFactorList +from twilio.rest.verify.v2.service.new_verify_factor import NewVerifyFactorList from twilio.rest.verify.v2.service.rate_limit import RateLimitList from twilio.rest.verify.v2.service.verification import VerificationList from twilio.rest.verify.v2.service.verification_check import VerificationCheckList @@ -35,7 +40,7 @@ class ServiceInstance(InstanceResource): """ :ivar sid: The unique string that we created to identify the Service resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. - :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. **This value should not contain PII.** + :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. It cannot contain more than 4 (consecutive or non-consecutive) digits. **This value should not contain PII.** :ivar code_length: The length of the verification code to generate. :ivar lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. :ivar psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. @@ -48,6 +53,7 @@ class ServiceInstance(InstanceResource): :ivar totp: Configurations for the TOTP factors (channel) created under this Service. :ivar default_template_sid: :ivar whatsapp: + :ivar passkeys: :ivar verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. @@ -81,6 +87,7 @@ def __init__( self.totp: Optional[Dict[str, object]] = payload.get("totp") self.default_template_sid: Optional[str] = payload.get("default_template_sid") self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.passkeys: Optional[Dict[str, object]] = payload.get("passkeys") self.verify_event_subscription_enabled: Optional[bool] = payload.get( "verify_event_subscription_enabled" ) @@ -96,6 +103,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -131,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -149,6 +175,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -170,6 +214,12 @@ def update( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> "ServiceInstance": """ @@ -194,6 +244,12 @@ def update( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance @@ -218,6 +274,12 @@ def update( default_template_sid=default_template_sid, whatsapp_msg_service_sid=whatsapp_msg_service_sid, whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, verify_event_subscription_enabled=verify_event_subscription_enabled, ) @@ -242,6 +304,12 @@ async def update_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> "ServiceInstance": """ @@ -266,6 +334,12 @@ async def update_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance @@ -290,6 +364,192 @@ async def update_async( default_template_sid=default_template_sid, whatsapp_msg_service_sid=whatsapp_msg_service_sid, whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, verify_event_subscription_enabled=verify_event_subscription_enabled, ) @@ -300,6 +560,13 @@ def access_tokens(self) -> AccessTokenList: """ return self._proxy.access_tokens + @property + def approve_challenge(self) -> ApproveChallengeList: + """ + Access the approve_challenge + """ + return self._proxy.approve_challenge + @property def entities(self) -> EntityList: """ @@ -314,6 +581,27 @@ def messaging_configurations(self) -> MessagingConfigurationList: """ return self._proxy.messaging_configurations + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + return self._proxy.new_challenge + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + return self._proxy.new_factors + + @property + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + return self._proxy.new_verify_factors + @property def rate_limits(self) -> RateLimitList: """ @@ -370,13 +658,31 @@ def __init__(self, version: Version, sid: str): self._uri = "/Services/{sid}".format(**self._solution) self._access_tokens: Optional[AccessTokenList] = None + self._approve_challenge: Optional[ApproveChallengeList] = None self._entities: Optional[EntityList] = None self._messaging_configurations: Optional[MessagingConfigurationList] = None + self._new_challenge: Optional[NewChallengeList] = None + self._new_factors: Optional[NewFactorList] = None + self._new_verify_factors: Optional[NewVerifyFactorList] = None self._rate_limits: Optional[RateLimitList] = None self._verifications: Optional[VerificationList] = None self._verification_checks: Optional[VerificationCheckList] = None self._webhooks: Optional[WebhookList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -384,10 +690,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -396,56 +724,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ServiceInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ServiceInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ServiceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ServiceInstance + Fetch the ServiceInstance and return response metadata - :returns: The fetched ServiceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() return ServiceInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, code_length: Union[int, object] = values.unset, @@ -466,33 +848,19 @@ def update( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** - :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. - :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. - :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. - :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. - :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. - :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. - :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** - :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. - :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. - :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) - :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) - :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. - :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds - :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 - :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 - :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. - :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. - :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. - :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -520,6 +888,12 @@ def update( "DefaultTemplateSid": default_template_sid, "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( verify_event_subscription_enabled ), @@ -531,13 +905,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, code_length: Union[int, object] = values.unset, @@ -558,10 +930,16 @@ async def update_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -582,10 +960,173 @@ async def update_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -612,6 +1153,12 @@ async def update_async( "DefaultTemplateSid": default_template_sid, "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( verify_event_subscription_enabled ), @@ -623,61 +1170,290 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def access_tokens(self) -> AccessTokenList: - """ - Access the access_tokens + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ - if self._access_tokens is None: - self._access_tokens = AccessTokenList( - self._version, - self._solution["sid"], - ) - return self._access_tokens + Asynchronous coroutine to update the ServiceInstance - @property - def entities(self) -> EntityList: - """ - Access the entities - """ - if self._entities is None: - self._entities = EntityList( - self._version, - self._solution["sid"], - ) - return self._entities + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - @property - def messaging_configurations(self) -> MessagingConfigurationList: - """ - Access the messaging_configurations + :returns: The updated ServiceInstance """ - if self._messaging_configurations is None: - self._messaging_configurations = MessagingConfigurationList( - self._version, - self._solution["sid"], - ) - return self._messaging_configurations + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - @property - def rate_limits(self) -> RateLimitList: - """ - Access the rate_limits + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: """ - if self._rate_limits is None: - self._rate_limits = RateLimitList( - self._version, - self._solution["sid"], - ) - return self._rate_limits + Asynchronous coroutine to update the ServiceInstance and return response metadata - @property + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + if self._access_tokens is None: + self._access_tokens = AccessTokenList( + self._version, + self._solution["sid"], + ) + return self._access_tokens + + @property + def approve_challenge(self) -> ApproveChallengeList: + """ + Access the approve_challenge + """ + if self._approve_challenge is None: + self._approve_challenge = ApproveChallengeList( + self._version, + self._solution["sid"], + ) + return self._approve_challenge + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + if self._messaging_configurations is None: + self._messaging_configurations = MessagingConfigurationList( + self._version, + self._solution["sid"], + ) + return self._messaging_configurations + + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + if self._new_challenge is None: + self._new_challenge = NewChallengeList( + self._version, + self._solution["sid"], + ) + return self._new_challenge + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["sid"], + ) + return self._new_factors + + @property + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + if self._new_verify_factors is None: + self._new_verify_factors = NewVerifyFactorList( + self._version, + self._solution["sid"], + ) + return self._new_verify_factors + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits + + @property def verifications(self) -> VerificationList: """ Access the verifications @@ -731,6 +1507,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -750,12 +1527,359 @@ def __init__(self, version: Version): :param version: Version that contains the resource - """ - super().__init__(version) + """ + super().__init__(version) + + self._uri = "/Services" + + def _create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - self._uri = "/Services" + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def create( + async def create_async( self, friendly_name: str, code_length: Union[int, object] = values.unset, @@ -776,10 +1900,16 @@ def create( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Create the ServiceInstance + Asynchronously create the ServiceInstance :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -800,54 +1930,47 @@ def create( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": serialize.boolean_to_string(lookup_enabled), - "SkipSmsToLandlines": serialize.boolean_to_string( - skip_sms_to_landlines - ), - "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), - "TtsName": tts_name, - "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), - "DoNotShareWarningEnabled": serialize.boolean_to_string( - do_not_share_warning_enabled - ), - "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), - "Push.IncludeDate": serialize.boolean_to_string(push_include_date), - "Push.ApnCredentialSid": push_apn_credential_sid, - "Push.FcmCredentialSid": push_fcm_credential_sid, - "Totp.Issuer": totp_issuer, - "Totp.TimeStep": totp_time_step, - "Totp.CodeLength": totp_code_length, - "Totp.Skew": totp_skew, - "DefaultTemplateSid": default_template_sid, - "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, - "Whatsapp.From": whatsapp_from, - "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( - verify_event_subscription_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, ) - return ServiceInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, friendly_name: str, code_length: Union[int, object] = values.unset, @@ -868,10 +1991,16 @@ async def create_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Asynchronously create the ServiceInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -892,52 +2021,46 @@ async def create_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": serialize.boolean_to_string(lookup_enabled), - "SkipSmsToLandlines": serialize.boolean_to_string( - skip_sms_to_landlines - ), - "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), - "TtsName": tts_name, - "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), - "DoNotShareWarningEnabled": serialize.boolean_to_string( - do_not_share_warning_enabled - ), - "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), - "Push.IncludeDate": serialize.boolean_to_string(push_include_date), - "Push.ApnCredentialSid": push_apn_credential_sid, - "Push.FcmCredentialSid": push_fcm_credential_sid, - "Totp.Issuer": totp_issuer, - "Totp.TimeStep": totp_time_step, - "Totp.CodeLength": totp_code_length, - "Totp.Skew": totp_skew, - "DefaultTemplateSid": default_template_sid, - "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, - "Whatsapp.From": whatsapp_from, - "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( - verify_event_subscription_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - headers["Content-Type"] = "application/x-www-form-urlencoded" - - headers["Accept"] = "application/json" - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, ) - - return ServiceInstance(self._version, payload) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -989,6 +2112,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -1008,6 +2181,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1034,6 +2208,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1042,6 +2217,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -1108,6 +2333,76 @@ async def page_async( ) return ServicePage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ServicePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ServicePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ServicePage: """ Retrieve a specific page of ServiceInstance records from the API. diff --git a/twilio/rest/verify/v2/service/access_token.py b/twilio/rest/verify/v2/service/access_token.py index 45a0094e52..a5ecc856b6 100644 --- a/twilio/rest/verify/v2/service/access_token.py +++ b/twilio/rest/verify/v2/service/access_token.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AccessTokenContext] = None @property @@ -103,6 +105,24 @@ async def fetch_async(self) -> "AccessTokenInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,20 +154,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) - def fetch(self) -> AccessTokenInstance: + def _fetch(self) -> tuple: """ - Fetch the AccessTokenInstance + Internal helper for fetch operation - - :returns: The fetched AccessTokenInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> AccessTokenInstance: + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + payload, _, _ = self._fetch() return AccessTokenInstance( self._version, payload, @@ -155,22 +185,46 @@ def fetch(self) -> AccessTokenInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> AccessTokenInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the AccessTokenInstance + Fetch the AccessTokenInstance and return response metadata - :returns: The fetched AccessTokenInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> AccessTokenInstance: + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + payload, _, _ = await self._fetch_async() return AccessTokenInstance( self._version, payload, @@ -178,6 +232,22 @@ async def fetch_async(self) -> AccessTokenInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccessTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -206,22 +276,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) - def create( + def _create( self, identity: str, factor_type: "AccessTokenInstance.FactorTypes", factor_friendly_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> AccessTokenInstance: + ) -> tuple: """ - Create the AccessTokenInstance - - :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. - :param factor_type: - :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token - :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + Internal helper for create operation - :returns: The created AccessTokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -238,30 +304,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) return AccessTokenInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, factor_type: "AccessTokenInstance.FactorTypes", factor_friendly_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> AccessTokenInstance: + ) -> ApiResponse: """ - Asynchronously create the AccessTokenInstance + Create the AccessTokenInstance and return response metadata :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. :param factor_type: :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. - :returns: The created AccessTokenInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -278,14 +391,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Asynchronously create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) return AccessTokenInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AccessTokenInstance and return response metadata + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> AccessTokenContext: """ Constructs a AccessTokenContext diff --git a/twilio/rest/verify/v2/service/approve_challenge.py b/twilio/rest/verify/v2/service/approve_challenge.py new file mode 100644 index 0000000000..52af951f0c --- /dev/null +++ b/twilio/rest/verify/v2/service/approve_challenge.py @@ -0,0 +1,346 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApproveChallengeInstance(InstanceResource): + + class ApprovePasskeysChallengeRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["ApproveChallengeInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["ApproveChallengeInstance.str"] = payload.get("type") + self.response: Optional[ + ApproveChallengeList.ApprovePasskeysChallengeRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class ApprovePasskeysChallengeRequestResponse(object): + """ + :ivar authenticator_data: The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar signature: An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + :ivar user_handle: The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.authenticator_data: Optional[str] = payload.get("authenticatorData") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.signature: Optional[str] = payload.get("signature") + self.user_handle: Optional[str] = payload.get("userHandle") + + def to_dict(self): + return { + "authenticatorData": self.authenticator_data, + "clientDataJSON": self.client_data_json, + "signature": self.signature, + "userHandle": self.user_handle, + } + + """ + :ivar sid: A 34 character string that uniquely identifies this Challenge. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. + :ivar factor_sid: The unique SID identifier of the Factor. + :ivar date_created: The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_responded: The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar status: The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + :ivar responded_reason: Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + :ivar details: Details provided to give context about the Challenge. + :ivar hidden_details: Details provided to give context about the Challenge. + :ivar metadata: Custom metadata associated with the challenge. + :ivar factor_type: The Factor Type of this Challenge. Currently `push` and `totp` are supported. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + :ivar options: An object that contains challenge options. Currently only used for `passkeys`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_responded: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_responded") + ) + self.expiration_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("expiration_date") + ) + self.status: Optional["ApproveChallengeInstance.str"] = payload.get("status") + self.responded_reason: Optional["ApproveChallengeInstance.str"] = payload.get( + "responded_reason" + ) + self.details: Optional[Dict[str, object]] = payload.get("details") + self.hidden_details: Optional[Dict[str, object]] = payload.get("hidden_details") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.factor_type: Optional["ApproveChallengeInstance.str"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.options: Optional[Dict[str, object]] = payload.get("options") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.ApproveChallengeInstance {}>".format(context) + + +class ApproveChallengeList(ListResource): + + class ApprovePasskeysChallengeRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["ApproveChallengeInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["ApproveChallengeInstance.str"] = payload.get("type") + self.response: Optional[ + ApproveChallengeList.ApprovePasskeysChallengeRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class ApprovePasskeysChallengeRequestResponse(object): + """ + :ivar authenticator_data: The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar signature: An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + :ivar user_handle: The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.authenticator_data: Optional[str] = payload.get("authenticatorData") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.signature: Optional[str] = payload.get("signature") + self.user_handle: Optional[str] = payload.get("userHandle") + + def to_dict(self): + return { + "authenticatorData": self.authenticator_data, + "clientDataJSON": self.client_data_json, + "signature": self.signature, + "userHandle": self.user_handle, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ApproveChallengeList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Passkeys/ApproveChallenge".format( + **self._solution + ) + + def _update( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = approve_passkeys_challenge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApproveChallengeInstance: + """ + Update the ApproveChallengeInstance + + :param approve_passkeys_challenge_request: + + :returns: The updated ApproveChallengeInstance + """ + payload, _, _ = self._update( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + return ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def update_with_http_info( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApiResponse: + """ + Update the ApproveChallengeInstance and return response metadata + + :param approve_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + instance = ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = approve_passkeys_challenge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApproveChallengeInstance: + """ + Asynchronously update the ApproveChallengeInstance + + :param approve_passkeys_challenge_request: + + :returns: The updated ApproveChallengeInstance + """ + payload, _, _ = await self._update_async( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + return ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def update_with_http_info_async( + self, approve_passkeys_challenge_request: ApprovePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronously update the ApproveChallengeInstance and return response metadata + + :param approve_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + approve_passkeys_challenge_request=approve_passkeys_challenge_request + ) + instance = ApproveChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.ApproveChallengeList>" diff --git a/twilio/rest/verify/v2/service/entity/__init__.py b/twilio/rest/verify/v2/service/entity/__init__.py index fa4bc1df12..f7f506f57a 100644 --- a/twilio/rest/verify/v2/service/entity/__init__.py +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "identity": identity or self.identity, } + self._context: Optional[EntityContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EntityInstance": """ Fetch the EntityInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "EntityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def challenges(self) -> ChallengeList: """ @@ -173,6 +211,20 @@ def __init__(self, version: Version, service_sid: str, identity: str): self._factors: Optional[FactorList] = None self._new_factors: Optional[NewFactorList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EntityInstance @@ -180,10 +232,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EntityInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -192,27 +266,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> EntityInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the EntityInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched EntityInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> EntityInstance: + """ + Fetch the EntityInstance + + :returns: The fetched EntityInstance + """ + payload, _, _ = self._fetch() return EntityInstance( self._version, payload, @@ -220,22 +310,46 @@ def fetch(self) -> EntityInstance: identity=self._solution["identity"], ) - async def fetch_async(self) -> EntityInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the EntityInstance + Fetch the EntityInstance and return response metadata - :returns: The fetched EntityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> EntityInstance: + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + payload, _, _ = await self._fetch_async() return EntityInstance( self._version, payload, @@ -243,6 +357,22 @@ async def fetch_async(self) -> EntityInstance: identity=self._solution["identity"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EntityInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def challenges(self) -> ChallengeList: """ @@ -300,6 +430,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: :param payload: Payload response from the API """ + return EntityInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -331,13 +462,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Entities".format(**self._solution) - def create(self, identity: str) -> EntityInstance: + def _create(self, identity: str) -> tuple: """ - Create the EntityInstance + Internal helper for create operation - :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. - - :returns: The created EntityInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -351,21 +481,43 @@ def create(self, identity: str) -> EntityInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, identity: str) -> EntityInstance: + """ + Create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + payload, _, _ = self._create(identity=identity) return EntityInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async(self, identity: str) -> EntityInstance: + def create_with_http_info(self, identity: str) -> ApiResponse: """ - Asynchronously create the EntityInstance + Create the EntityInstance and return response metadata :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. - :returns: The created EntityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(identity=identity) + instance = EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, identity: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -379,14 +531,37 @@ async def create_async(self, identity: str) -> EntityInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, identity: str) -> EntityInstance: + """ + Asynchronously create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + payload, _, _ = await self._create_async(identity=identity) return EntityInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async(self, identity: str) -> ApiResponse: + """ + Asynchronously create the EntityInstance and return response metadata + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(identity=identity) + instance = EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -437,6 +612,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -456,6 +681,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -482,6 +708,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -490,6 +717,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EntityInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -521,7 +798,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return EntityPage(self._version, response, self._solution) + return EntityPage(self._version, response, solution=self._solution) async def page_async( self, @@ -554,7 +831,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return EntityPage(self._version, response, self._solution) + return EntityPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EntityPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = EntityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with EntityPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = EntityPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> EntityPage: """ @@ -566,7 +913,7 @@ def get_page(self, target_url: str) -> EntityPage: :returns: Page of EntityInstance """ response = self._version.domain.twilio.request("GET", target_url) - return EntityPage(self._version, response, self._solution) + return EntityPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> EntityPage: """ @@ -578,7 +925,7 @@ async def get_page_async(self, target_url: str) -> EntityPage: :returns: Page of EntityInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return EntityPage(self._version, response, self._solution) + return EntityPage(self._version, response, solution=self._solution) def get(self, identity: str) -> EntityContext: """ diff --git a/twilio/rest/verify/v2/service/entity/challenge/__init__.py b/twilio/rest/verify/v2/service/entity/challenge/__init__.py index 146a95d959..9940cbf831 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/__init__.py +++ b/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -39,6 +40,7 @@ class ChallengeStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class ListOrders(object): ASC = "asc" @@ -113,6 +115,7 @@ def __init__( "identity": identity, "sid": sid or self.sid, } + self._context: Optional[ChallengeContext] = None @property @@ -150,6 +153,24 @@ async def fetch_async(self) -> "ChallengeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, auth_payload: Union[str, object] = values.unset, @@ -186,6 +207,42 @@ async def update_async( metadata=metadata, ) + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChallengeInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + metadata=metadata, + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChallengeInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + auth_payload=auth_payload, + metadata=metadata, + ) + @property def notifications(self) -> NotificationList: """ @@ -230,20 +287,30 @@ def __init__(self, version: Version, service_sid: str, identity: str, sid: str): self._notifications: Optional[NotificationList] = None - def fetch(self) -> ChallengeInstance: + def _fetch(self) -> tuple: """ - Fetch the ChallengeInstance + Internal helper for fetch operation - - :returns: The fetched ChallengeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> ChallengeInstance: + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + payload, _, _ = self._fetch() return ChallengeInstance( self._version, payload, @@ -252,22 +319,47 @@ def fetch(self) -> ChallengeInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ChallengeInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ChallengeInstance + Fetch the ChallengeInstance and return response metadata - :returns: The fetched ChallengeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ChallengeInstance: + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + payload, _, _ = await self._fetch_async() return ChallengeInstance( self._version, payload, @@ -276,18 +368,33 @@ async def fetch_async(self) -> ChallengeInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChallengeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, auth_payload: Union[str, object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> ChallengeInstance: + ) -> tuple: """ - Update the ChallengeInstance - - :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length - :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + Internal helper for update operation - :returns: The updated ChallengeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -302,10 +409,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + payload, _, _ = self._update(auth_payload=auth_payload, metadata=metadata) return ChallengeInstance( self._version, payload, @@ -314,18 +435,41 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, auth_payload: Union[str, object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> ChallengeInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ChallengeInstance + Update the ChallengeInstance and return response metadata :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. - :returns: The updated ChallengeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + auth_payload=auth_payload, metadata=metadata + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -340,10 +484,26 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronous coroutine to update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + payload, _, _ = await self._update_async( + auth_payload=auth_payload, metadata=metadata + ) return ChallengeInstance( self._version, payload, @@ -352,6 +512,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChallengeInstance and return response metadata + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + auth_payload=auth_payload, metadata=metadata + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def notifications(self) -> NotificationList: """ @@ -384,6 +569,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChallengeInstance: :param payload: Payload response from the API """ + return ChallengeInstance( self._version, payload, @@ -422,7 +608,7 @@ def __init__(self, version: Version, service_sid: str, identity: str): **self._solution ) - def create( + def _create( self, factor_sid: str, expiration_date: Union[datetime, object] = values.unset, @@ -430,18 +616,12 @@ def create( details_fields: Union[List[object], object] = values.unset, hidden_details: Union[object, object] = values.unset, auth_payload: Union[str, object] = values.unset, - ) -> ChallengeInstance: + ) -> tuple: """ - Create the ChallengeInstance + Internal helper for create operation - :param factor_sid: The unique SID identifier of the Factor. - :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. - :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length - :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. - :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length - :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. - - :returns: The created ChallengeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -462,10 +642,39 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + payload, _, _ = self._create( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) return ChallengeInstance( self._version, payload, @@ -473,7 +682,7 @@ def create( identity=self._solution["identity"], ) - async def create_async( + def create_with_http_info( self, factor_sid: str, expiration_date: Union[datetime, object] = values.unset, @@ -481,9 +690,9 @@ async def create_async( details_fields: Union[List[object], object] = values.unset, hidden_details: Union[object, object] = values.unset, auth_payload: Union[str, object] = values.unset, - ) -> ChallengeInstance: + ) -> ApiResponse: """ - Asynchronously create the ChallengeInstance + Create the ChallengeInstance and return response metadata :param factor_sid: The unique SID identifier of the Factor. :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. @@ -492,7 +701,38 @@ async def create_async( :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. - :returns: The created ChallengeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -513,10 +753,39 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronously create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + payload, _, _ = await self._create_async( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) return ChallengeInstance( self._version, payload, @@ -524,6 +793,43 @@ async def create_async( identity=self._solution["identity"], ) + async def create_with_http_info_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChallengeInstance and return response metadata + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, factor_sid: Union[str, object] = values.unset, @@ -596,6 +902,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChallengeInstance and returns headers from first page + + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChallengeInstance and returns headers from first page + + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, factor_sid: Union[str, object] = values.unset, @@ -621,6 +997,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( factor_sid=factor_sid, @@ -656,6 +1033,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -667,6 +1045,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChallengeInstance and returns headers from first page + + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChallengeInstance and returns headers from first page + + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, factor_sid: Union[str, object] = values.unset, @@ -707,7 +1153,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ChallengePage(self._version, response, self._solution) + return ChallengePage(self._version, response, solution=self._solution) async def page_async( self, @@ -749,7 +1195,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ChallengePage(self._version, response, self._solution) + return ChallengePage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChallengePage, status code, and headers + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ChallengePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ChallengePage, status code, and headers + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ChallengePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ChallengePage: """ @@ -761,7 +1295,7 @@ def get_page(self, target_url: str) -> ChallengePage: :returns: Page of ChallengeInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChallengePage(self._version, response, self._solution) + return ChallengePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChallengePage: """ @@ -773,7 +1307,7 @@ async def get_page_async(self, target_url: str) -> ChallengePage: :returns: Page of ChallengeInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChallengePage(self._version, response, self._solution) + return ChallengePage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChallengeContext: """ diff --git a/twilio/rest/verify/v2/service/entity/challenge/notification.py b/twilio/rest/verify/v2/service/entity/challenge/notification.py index 3802cc1a08..4250597da6 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/notification.py +++ b/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,13 +99,12 @@ def __init__( **self._solution ) - def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance: + def _create(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Create the NotificationInstance - - :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + Internal helper for create operation - :returns: The created NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -118,10 +118,19 @@ def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance: + """ + Create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + payload, _, _ = self._create(ttl=ttl) return NotificationInstance( self._version, payload, @@ -130,15 +139,32 @@ def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance challenge_sid=self._solution["challenge_sid"], ) - async def create_async( + def create_with_http_info( self, ttl: Union[int, object] = values.unset - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronously create the NotificationInstance + Create the NotificationInstance and return response metadata :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. - :returns: The created NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(ttl=ttl) + instance = NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -152,10 +178,21 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + payload, _, _ = await self._create_async(ttl=ttl) return NotificationInstance( self._version, payload, @@ -164,6 +201,26 @@ async def create_async( challenge_sid=self._solution["challenge_sid"], ) + async def create_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NotificationInstance and return response metadata + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(ttl=ttl) + instance = NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/verify/v2/service/entity/factor.py b/twilio/rest/verify/v2/service/entity/factor.py index 7bf91cd870..823dd53f69 100644 --- a/twilio/rest/verify/v2/service/entity/factor.py +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class FactorStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class TotpAlgorithms(object): SHA1 = "sha1" @@ -88,6 +90,7 @@ def __init__( "identity": identity, "sid": sid or self.sid, } + self._context: Optional[FactorContext] = None @property @@ -125,6 +128,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FactorInstance": """ Fetch the FactorInstance @@ -143,6 +164,24 @@ async def fetch_async(self) -> "FactorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, auth_payload: Union[str, object] = values.unset, @@ -221,6 +260,84 @@ async def update_async( config_notification_platform=config_notification_platform, ) + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FactorInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FactorInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -254,6 +371,20 @@ def __init__(self, version: Version, service_sid: str, identity: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FactorInstance @@ -261,10 +392,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FactorInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -273,27 +426,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> FactorInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the FactorInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched FactorInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> FactorInstance: + """ + Fetch the FactorInstance + + :returns: The fetched FactorInstance + """ + payload, _, _ = self._fetch() return FactorInstance( self._version, payload, @@ -302,22 +471,47 @@ def fetch(self) -> FactorInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> FactorInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the FactorInstance + Fetch the FactorInstance and return response metadata - :returns: The fetched FactorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> FactorInstance: + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + payload, _, _ = await self._fetch_async() return FactorInstance( self._version, payload, @@ -326,7 +520,24 @@ async def fetch_async(self) -> FactorInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FactorInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, auth_payload: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -337,21 +548,12 @@ def update( config_code_length: Union[int, object] = values.unset, config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, config_notification_platform: Union[str, object] = values.unset, - ) -> FactorInstance: + ) -> tuple: """ - Update the FactorInstance + Internal helper for update operation - :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. - :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. - :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. - :param config_sdk_version: The Verify Push SDK version used to configure the factor - :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive - :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive - :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive - :param config_alg: - :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. - - :returns: The updated FactorInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -373,10 +575,48 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + payload, _, _ = self._update( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) return FactorInstance( self._version, payload, @@ -385,7 +625,7 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, auth_payload: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -396,9 +636,9 @@ async def update_async( config_code_length: Union[int, object] = values.unset, config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, config_notification_platform: Union[str, object] = values.unset, - ) -> FactorInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the FactorInstance + Update the FactorInstance and return response metadata :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. @@ -410,7 +650,45 @@ async def update_async( :param config_alg: :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. - :returns: The updated FactorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -432,10 +710,48 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + payload, _, _ = await self._update_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) return FactorInstance( self._version, payload, @@ -444,6 +760,53 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FactorInstance and return response metadata + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + instance = FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -462,6 +825,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: :param payload: Payload response from the API """ + return FactorInstance( self._version, payload, @@ -550,6 +914,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -569,6 +983,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -595,6 +1010,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -603,6 +1019,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists FactorInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -634,7 +1100,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return FactorPage(self._version, response, self._solution) + return FactorPage(self._version, response, solution=self._solution) async def page_async( self, @@ -667,7 +1133,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return FactorPage(self._version, response, self._solution) + return FactorPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FactorPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FactorPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with FactorPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FactorPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> FactorPage: """ @@ -679,7 +1215,7 @@ def get_page(self, target_url: str) -> FactorPage: :returns: Page of FactorInstance """ response = self._version.domain.twilio.request("GET", target_url) - return FactorPage(self._version, response, self._solution) + return FactorPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> FactorPage: """ @@ -691,7 +1227,7 @@ async def get_page_async(self, target_url: str) -> FactorPage: :returns: Page of FactorInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return FactorPage(self._version, response, self._solution) + return FactorPage(self._version, response, solution=self._solution) def get(self, sid: str) -> FactorContext: """ diff --git a/twilio/rest/verify/v2/service/entity/new_factor.py b/twilio/rest/verify/v2/service/entity/new_factor.py index 2a2d77d512..79184c0e74 100644 --- a/twilio/rest/verify/v2/service/entity/new_factor.py +++ b/twilio/rest/verify/v2/service/entity/new_factor.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,6 +31,7 @@ class FactorStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class NotificationPlatforms(object): APN = "apn" @@ -48,6 +50,7 @@ class TotpAlgorithms(object): :ivar entity_sid: The unique SID identifier of the Entity. :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. :ivar binding: Contains the `factor_type` specific secret and metadata. For push, this is `binding.public_key` and `binding.alg`. For totp, this is `binding.secret` and `binding.uri`. The `binding.uri` property is generated following the [google authenticator key URI format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), and `Factor.friendly_name` is used for the “accountname” value and `Service.friendly_name` or `Service.totp.issuer` is used for the `issuer` value. The Binding property is ONLY returned upon Factor creation. + :ivar options: :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. @@ -69,6 +72,7 @@ def __init__( self.entity_sid: Optional[str] = payload.get("entity_sid") self.identity: Optional[str] = payload.get("identity") self.binding: Optional[Dict[str, object]] = payload.get("binding") + self.options: Optional[Dict[str, object]] = payload.get("options") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -123,7 +127,7 @@ def __init__(self, version: Version, service_sid: str, identity: str): **self._solution ) - def create( + def _create( self, friendly_name: str, factor_type: "NewFactorInstance.FactorTypes", @@ -141,26 +145,12 @@ def create( config_code_length: Union[int, object] = values.unset, config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> NewFactorInstance: + ) -> tuple: """ - Create the NewFactorInstance - - :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. - :param factor_type: - :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` - :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` - :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. - :param config_notification_platform: - :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. - :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` - :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` - :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` - :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` - :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` - :param config_alg: - :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + Internal helper for create operation - :returns: The created NewFactorInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -187,10 +177,65 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) return NewFactorInstance( self._version, payload, @@ -198,7 +243,7 @@ def create( identity=self._solution["identity"], ) - async def create_async( + def create_with_http_info( self, friendly_name: str, factor_type: "NewFactorInstance.FactorTypes", @@ -216,9 +261,9 @@ async def create_async( config_code_length: Union[int, object] = values.unset, config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> NewFactorInstance: + ) -> ApiResponse: """ - Asynchronously create the NewFactorInstance + Create the NewFactorInstance and return response metadata :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. :param factor_type: @@ -235,7 +280,56 @@ async def create_async( :param config_alg: :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. - :returns: The created NewFactorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + instance = NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -262,10 +356,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Asynchronously create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) return NewFactorInstance( self._version, payload, @@ -273,6 +422,69 @@ async def create_async( identity=self._solution["identity"], ) + async def create_with_http_info_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NewFactorInstance and return response metadata + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + instance = NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/verify/v2/service/messaging_configuration.py b/twilio/rest/verify/v2/service/messaging_configuration.py index 03f494f6e9..43920cc5b9 100644 --- a/twilio/rest/verify/v2/service/messaging_configuration.py +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "service_sid": service_sid, "country": country or self.country, } + self._context: Optional[MessagingConfigurationContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessagingConfigurationInstance": """ Fetch the MessagingConfigurationInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "MessagingConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, messaging_service_sid: str) -> "MessagingConfigurationInstance": """ Update the MessagingConfigurationInstance @@ -138,6 +176,32 @@ async def update_async( messaging_service_sid=messaging_service_sid, ) + def update_with_http_info(self, messaging_service_sid: str) -> ApiResponse: + """ + Update the MessagingConfigurationInstance with HTTP info + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + messaging_service_sid=messaging_service_sid, + ) + + async def update_with_http_info_async( + self, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance with HTTP info + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + messaging_service_sid=messaging_service_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -169,6 +233,20 @@ def __init__(self, version: Version, service_sid: str, country: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessagingConfigurationInstance @@ -176,10 +254,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessagingConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -188,27 +288,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> MessagingConfigurationInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the MessagingConfigurationInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched MessagingConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> MessagingConfigurationInstance: + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + payload, _, _ = self._fetch() return MessagingConfigurationInstance( self._version, payload, @@ -216,22 +332,46 @@ def fetch(self) -> MessagingConfigurationInstance: country=self._solution["country"], ) - async def fetch_async(self) -> MessagingConfigurationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the MessagingConfigurationInstance + Fetch the MessagingConfigurationInstance and return response metadata - :returns: The fetched MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + payload, _, _ = await self._fetch_async() return MessagingConfigurationInstance( self._version, payload, @@ -239,13 +379,28 @@ async def fetch_async(self) -> MessagingConfigurationInstance: country=self._solution["country"], ) - def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the MessagingConfigurationInstance + Asynchronous coroutine to fetch the MessagingConfigurationInstance and return response metadata - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - :returns: The updated MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, messaging_service_sid: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -259,10 +414,19 @@ def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: + """ + Update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + payload, _, _ = self._update(messaging_service_sid=messaging_service_sid) return MessagingConfigurationInstance( self._version, payload, @@ -270,15 +434,31 @@ def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: country=self._solution["country"], ) - async def update_async( - self, messaging_service_sid: str - ) -> MessagingConfigurationInstance: + def update_with_http_info(self, messaging_service_sid: str) -> ApiResponse: """ - Asynchronous coroutine to update the MessagingConfigurationInstance + Update the MessagingConfigurationInstance and return response metadata :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - :returns: The updated MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, messaging_service_sid: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -292,10 +472,23 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + payload, _, _ = await self._update_async( + messaging_service_sid=messaging_service_sid + ) return MessagingConfigurationInstance( self._version, payload, @@ -303,6 +496,27 @@ async def update_async( country=self._solution["country"], ) + async def update_with_http_info_async( + self, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance and return response metadata + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -321,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessagingConfigurationInstanc :param payload: Payload response from the API """ + return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -354,16 +569,12 @@ def __init__(self, version: Version, service_sid: str): **self._solution ) - def create( - self, country: str, messaging_service_sid: str - ) -> MessagingConfigurationInstance: + def _create(self, country: str, messaging_service_sid: str) -> tuple: """ - Create the MessagingConfigurationInstance + Internal helper for create operation - :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - - :returns: The created MessagingConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -378,24 +589,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, country: str, messaging_service_sid: str - ) -> MessagingConfigurationInstance: + ) -> ApiResponse: """ - Asynchronously create the MessagingConfigurationInstance + Create the MessagingConfigurationInstance and return response metadata :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - :returns: The created MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, country: str, messaging_service_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -410,14 +650,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronously create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, country: str, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronously create the MessagingConfigurationInstance and return response metadata + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -468,6 +741,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessagingConfigurationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MessagingConfigurationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -487,6 +810,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -513,6 +837,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -521,6 +846,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessagingConfigurationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MessagingConfigurationInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -552,7 +927,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagingConfigurationPage(self._version, response, self._solution) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -585,7 +962,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return MessagingConfigurationPage(self._version, response, self._solution) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagingConfigurationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagingConfigurationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagingConfigurationPage: """ @@ -597,7 +1050,9 @@ def get_page(self, target_url: str) -> MessagingConfigurationPage: :returns: Page of MessagingConfigurationInstance """ response = self._version.domain.twilio.request("GET", target_url) - return MessagingConfigurationPage(self._version, response, self._solution) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: """ @@ -609,7 +1064,9 @@ async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: :returns: Page of MessagingConfigurationInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagingConfigurationPage(self._version, response, self._solution) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) def get(self, country: str) -> MessagingConfigurationContext: """ diff --git a/twilio/rest/verify/v2/service/new_challenge.py b/twilio/rest/verify/v2/service/new_challenge.py new file mode 100644 index 0000000000..74107dd044 --- /dev/null +++ b/twilio/rest/verify/v2/service/new_challenge.py @@ -0,0 +1,404 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewChallengeInstance(InstanceResource): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + """ + :ivar sid: A 34 character string that uniquely identifies this Challenge. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. + :ivar factor_sid: The unique SID identifier of the Factor. + :ivar date_created: The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_responded: The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar status: The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + :ivar responded_reason: Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + :ivar details: Details provided to give context about the Challenge. + :ivar hidden_details: Details provided to give context about the Challenge. + :ivar metadata: Custom metadata associated with the challenge. + :ivar factor_type: The Factor Type of this Challenge. Currently `push` and `totp` are supported. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + :ivar options: An object that contains challenge options. Currently only used for `passkeys`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_responded: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_responded") + ) + self.expiration_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("expiration_date") + ) + self.status: Optional["ApproveChallengeInstance.str"] = payload.get("status") + self.responded_reason: Optional["ApproveChallengeInstance.str"] = payload.get( + "responded_reason" + ) + self.details: Optional[Dict[str, object]] = payload.get("details") + self.hidden_details: Optional[Dict[str, object]] = payload.get("hidden_details") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.factor_type: Optional["ApproveChallengeInstance.str"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.options: Optional[Dict[str, object]] = payload.get("options") + + self._solution = { + "service_sid": service_sid, + } + + self._context: Optional[NewChallengeContext] = None + + @property + def _proxy(self) -> "NewChallengeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NewChallengeContext for this NewChallengeInstance + """ + if self._context is None: + self._context = NewChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + ) + return self._context + + def create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> "NewChallengeInstance": + """ + Create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + return self._proxy.create( + create_passkeys_challenge_request, + ) + + async def create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> "NewChallengeInstance": + """ + Asynchronous coroutine to create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + return await self._proxy.create_async( + create_passkeys_challenge_request, + ) + + def create_with_http_info( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Create the NewChallengeInstance with HTTP info + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + create_passkeys_challenge_request, + ) + + async def create_with_http_info_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to create the NewChallengeInstance with HTTP info + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + create_passkeys_challenge_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NewChallengeInstance {}>".format(context) + + +class NewChallengeContext(InstanceContext): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewChallengeContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Passkeys/Challenges".format( + **self._solution + ) + + def _create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_passkeys_challenge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> NewChallengeInstance: + """ + Create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + payload, _, _ = self._create( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + return NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Create the NewChallengeInstance and return response metadata + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + instance = NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_passkeys_challenge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> NewChallengeInstance: + """ + Asynchronous coroutine to create the NewChallengeInstance + + :param create_passkeys_challenge_request: + + :returns: The created NewChallengeInstance + """ + payload, _, _ = await self._create_async( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + return NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, create_passkeys_challenge_request: CreatePasskeysChallengeRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to create the NewChallengeInstance and return response metadata + + :param create_passkeys_challenge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_passkeys_challenge_request=create_passkeys_challenge_request + ) + instance = NewChallengeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NewChallengeContext {}>".format(context) + + +class NewChallengeList(ListResource): + + class CreatePasskeysChallengeRequest(object): + """ + :ivar identity: + :ivar factor_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + + def to_dict(self): + return { + "identity": self.identity, + "factor_sid": self.factor_sid, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewChallengeList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + + def get(self) -> NewChallengeContext: + """ + Constructs a NewChallengeContext + + """ + return NewChallengeContext( + self._version, service_sid=self._solution["service_sid"] + ) + + def __call__(self) -> NewChallengeContext: + """ + Constructs a NewChallengeContext + + """ + return NewChallengeContext( + self._version, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.NewChallengeList>" diff --git a/twilio/rest/verify/v2/service/new_factor.py b/twilio/rest/verify/v2/service/new_factor.py new file mode 100644 index 0000000000..b5595bca5c --- /dev/null +++ b/twilio/rest/verify/v2/service/new_factor.py @@ -0,0 +1,372 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewFactorInstance(InstanceResource): + + class CreateNewPasskeysFactorRequest(object): + """ + :ivar friendly_name: + :ivar identity: + :ivar config: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity: Optional[str] = payload.get("identity") + self.config: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfig + ] = payload.get("config") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "identity": self.identity, + "config": self.config.to_dict() if self.config is not None else None, + } + + class CreateNewPasskeysFactorRequestConfig(object): + """ + :ivar relying_party: + :ivar authenticator_attachment: + :ivar discoverable_credentials: + :ivar user_verification: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.relying_party: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfigRelyingParty + ] = payload.get("relying_party") + self.authenticator_attachment: Optional["NewFactorInstance.str"] = ( + payload.get("authenticator_attachment") + ) + self.discoverable_credentials: Optional["NewFactorInstance.str"] = ( + payload.get("discoverable_credentials") + ) + self.user_verification: Optional["NewFactorInstance.str"] = payload.get( + "user_verification" + ) + + def to_dict(self): + return { + "relying_party": ( + self.relying_party.to_dict() + if self.relying_party is not None + else None + ), + "authenticator_attachment": self.authenticator_attachment, + "discoverable_credentials": self.discoverable_credentials, + "user_verification": self.user_verification, + } + + class CreateNewPasskeysFactorRequestConfigRelyingParty(object): + """ + :ivar id: + :ivar name: + :ivar origins: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.origins: Optional[List[str]] = payload.get("origins") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "origins": self.origins, + } + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. + :ivar binding: Contains the `factor_type` specific secret and metadata. The Binding property is ONLY returned upon Factor creation. + :ivar options: + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. + :ivar status: The Status of this Factor. One of `unverified` or `verified`. + :ivar factor_type: The Type of this Factor. Currently `push` and `totp` are supported. + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.binding: Optional[Dict[str, object]] = payload.get("binding") + self.options: Optional[Dict[str, object]] = payload.get("options") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["NewFactorInstance.str"] = payload.get("status") + self.factor_type: Optional["NewFactorInstance.str"] = payload.get("factor_type") + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NewFactorInstance {}>".format(context) + + +class NewFactorList(ListResource): + + class CreateNewPasskeysFactorRequest(object): + """ + :ivar friendly_name: + :ivar identity: + :ivar config: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity: Optional[str] = payload.get("identity") + self.config: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfig + ] = payload.get("config") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "identity": self.identity, + "config": self.config.to_dict() if self.config is not None else None, + } + + class CreateNewPasskeysFactorRequestConfig(object): + """ + :ivar relying_party: + :ivar authenticator_attachment: + :ivar discoverable_credentials: + :ivar user_verification: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.relying_party: Optional[ + NewFactorList.CreateNewPasskeysFactorRequestConfigRelyingParty + ] = payload.get("relying_party") + self.authenticator_attachment: Optional["NewFactorInstance.str"] = ( + payload.get("authenticator_attachment") + ) + self.discoverable_credentials: Optional["NewFactorInstance.str"] = ( + payload.get("discoverable_credentials") + ) + self.user_verification: Optional["NewFactorInstance.str"] = payload.get( + "user_verification" + ) + + def to_dict(self): + return { + "relying_party": ( + self.relying_party.to_dict() + if self.relying_party is not None + else None + ), + "authenticator_attachment": self.authenticator_attachment, + "discoverable_credentials": self.discoverable_credentials, + "user_verification": self.user_verification, + } + + class CreateNewPasskeysFactorRequestConfigRelyingParty(object): + """ + :ivar id: + :ivar name: + :ivar origins: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.origins: Optional[List[str]] = payload.get("origins") + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "origins": self.origins, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewFactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Passkeys/Factors".format(**self._solution) + + def _create( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_new_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> NewFactorInstance: + """ + Create the NewFactorInstance + + :param create_new_passkeys_factor_request: + + :returns: The created NewFactorInstance + """ + payload, _, _ = self._create( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + return NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> ApiResponse: + """ + Create the NewFactorInstance and return response metadata + + :param create_new_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + instance = NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_new_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> NewFactorInstance: + """ + Asynchronously create the NewFactorInstance + + :param create_new_passkeys_factor_request: + + :returns: The created NewFactorInstance + """ + payload, _, _ = await self._create_async( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + return NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_with_http_info_async( + self, create_new_passkeys_factor_request: CreateNewPasskeysFactorRequest + ) -> ApiResponse: + """ + Asynchronously create the NewFactorInstance and return response metadata + + :param create_new_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_new_passkeys_factor_request=create_new_passkeys_factor_request + ) + instance = NewFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.NewFactorList>" diff --git a/twilio/rest/verify/v2/service/new_verify_factor.py b/twilio/rest/verify/v2/service/new_verify_factor.py new file mode 100644 index 0000000000..703eabd3b0 --- /dev/null +++ b/twilio/rest/verify/v2/service/new_verify_factor.py @@ -0,0 +1,322 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewVerifyFactorInstance(InstanceResource): + + class VerifyPasskeysFactorRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["NewVerifyFactorInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["NewVerifyFactorInstance.str"] = payload.get("type") + self.response: Optional[ + NewVerifyFactorList.VerifyPasskeysFactorRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class VerifyPasskeysFactorRequestResponse(object): + """ + :ivar attestation_object: The authenticator data and an attestation statement for a new key pair generated by the authenticator. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar transports: An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.attestation_object: Optional[str] = payload.get("attestationObject") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.transports: Optional[List[Enumstr]] = payload.get("transports") + + def to_dict(self): + return { + "attestationObject": self.attestation_object, + "clientDataJSON": self.client_data_json, + "transports": self.transports, + } + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar status: The Status of this Factor. One of `unverified` or `verified`. + :ivar factor_type: The Type of this Factor. Currently `push` and `totp` are supported. + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["NewVerifyFactorInstance.str"] = payload.get("status") + self.factor_type: Optional["NewVerifyFactorInstance.str"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NewVerifyFactorInstance {}>".format(context) + + +class NewVerifyFactorList(ListResource): + + class VerifyPasskeysFactorRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["NewVerifyFactorInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["NewVerifyFactorInstance.str"] = payload.get("type") + self.response: Optional[ + NewVerifyFactorList.VerifyPasskeysFactorRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class VerifyPasskeysFactorRequestResponse(object): + """ + :ivar attestation_object: The authenticator data and an attestation statement for a new key pair generated by the authenticator. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar transports: An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.attestation_object: Optional[str] = payload.get("attestationObject") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.transports: Optional[List[Enumstr]] = payload.get("transports") + + def to_dict(self): + return { + "attestationObject": self.attestation_object, + "clientDataJSON": self.client_data_json, + "transports": self.transports, + } + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NewVerifyFactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Passkeys/VerifyFactor".format( + **self._solution + ) + + def _update( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = verify_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> NewVerifyFactorInstance: + """ + Update the NewVerifyFactorInstance + + :param verify_passkeys_factor_request: + + :returns: The updated NewVerifyFactorInstance + """ + payload, _, _ = self._update( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + return NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def update_with_http_info( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> ApiResponse: + """ + Update the NewVerifyFactorInstance and return response metadata + + :param verify_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + instance = NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = verify_passkeys_factor_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> NewVerifyFactorInstance: + """ + Asynchronously update the NewVerifyFactorInstance + + :param verify_passkeys_factor_request: + + :returns: The updated NewVerifyFactorInstance + """ + payload, _, _ = await self._update_async( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + return NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def update_with_http_info_async( + self, verify_passkeys_factor_request: VerifyPasskeysFactorRequest + ) -> ApiResponse: + """ + Asynchronously update the NewVerifyFactorInstance and return response metadata + + :param verify_passkeys_factor_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + verify_passkeys_factor_request=verify_passkeys_factor_request + ) + instance = NewVerifyFactorInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.NewVerifyFactorList>" diff --git a/twilio/rest/verify/v2/service/rate_limit/__init__.py b/twilio/rest/verify/v2/service/rate_limit/__init__.py index ced5ab6a64..e01a326d9e 100644 --- a/twilio/rest/verify/v2/service/rate_limit/__init__.py +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RateLimitContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RateLimitInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RateLimitInstance": """ Fetch the RateLimitInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "RateLimitInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RateLimitInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RateLimitInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, description: Union[str, object] = values.unset ) -> "RateLimitInstance": @@ -145,6 +183,34 @@ async def update_async( description=description, ) + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the RateLimitInstance with HTTP info + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RateLimitInstance with HTTP info + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) + @property def buckets(self) -> BucketList: """ @@ -183,6 +249,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._buckets: Optional[BucketList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RateLimitInstance @@ -190,10 +270,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RateLimitInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -202,27 +304,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RateLimitInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RateLimitInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RateLimitInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + :returns: The fetched RateLimitInstance + """ + payload, _, _ = self._fetch() return RateLimitInstance( self._version, payload, @@ -230,22 +348,46 @@ def fetch(self) -> RateLimitInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RateLimitInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RateLimitInstance + Fetch the RateLimitInstance and return response metadata - :returns: The fetched RateLimitInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RateLimitInstance: + """ + Asynchronous coroutine to fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + payload, _, _ = await self._fetch_async() return RateLimitInstance( self._version, payload, @@ -253,15 +395,28 @@ async def fetch_async(self) -> RateLimitInstance: sid=self._solution["sid"], ) - def update( - self, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RateLimitInstance + Asynchronous coroutine to fetch the RateLimitInstance and return response metadata - :param description: Description of this Rate Limit - :returns: The updated RateLimitInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, description: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -275,10 +430,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + payload, _, _ = self._update(description=description) return RateLimitInstance( self._version, payload, @@ -286,15 +452,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the RateLimitInstance + Update the RateLimitInstance and return response metadata :param description: Description of this Rate Limit - :returns: The updated RateLimitInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(description=description) + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -308,10 +492,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + payload, _, _ = await self._update_async(description=description) return RateLimitInstance( self._version, payload, @@ -319,6 +514,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RateLimitInstance and return response metadata + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + description=description + ) + instance = RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def buckets(self) -> BucketList: """ @@ -350,6 +566,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: :param payload: Payload response from the API """ + return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -381,16 +598,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) - def create( + def _create( self, unique_name: str, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + ) -> tuple: """ - Create the RateLimitInstance - - :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** - :param description: Description of this Rate Limit + Internal helper for create operation - :returns: The created RateLimitInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -405,24 +620,53 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + payload, _, _ = self._create(unique_name=unique_name, description=description) return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: str, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + ) -> ApiResponse: """ - Asynchronously create the RateLimitInstance + Create the RateLimitInstance and return response metadata :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** :param description: Description of this Rate Limit - :returns: The created RateLimitInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -437,14 +681,47 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, description=description + ) return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the RateLimitInstance and return response metadata + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -495,6 +772,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RateLimitInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RateLimitInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -514,6 +841,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -540,6 +868,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -548,6 +877,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RateLimitInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RateLimitInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -579,7 +958,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RateLimitPage(self._version, response, self._solution) + return RateLimitPage(self._version, response, solution=self._solution) async def page_async( self, @@ -612,7 +991,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RateLimitPage(self._version, response, self._solution) + return RateLimitPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RateLimitPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RateLimitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RateLimitPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RateLimitPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RateLimitPage: """ @@ -624,7 +1073,7 @@ def get_page(self, target_url: str) -> RateLimitPage: :returns: Page of RateLimitInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RateLimitPage(self._version, response, self._solution) + return RateLimitPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RateLimitPage: """ @@ -636,7 +1085,7 @@ async def get_page_async(self, target_url: str) -> RateLimitPage: :returns: Page of RateLimitInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RateLimitPage(self._version, response, self._solution) + return RateLimitPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RateLimitContext: """ diff --git a/twilio/rest/verify/v2/service/rate_limit/bucket.py b/twilio/rest/verify/v2/service/rate_limit/bucket.py index 4ac50cfc2f..9b47a70c3c 100644 --- a/twilio/rest/verify/v2/service/rate_limit/bucket.py +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "rate_limit_sid": rate_limit_sid, "sid": sid or self.sid, } + self._context: Optional[BucketContext] = None @property @@ -101,6 +103,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BucketInstance": """ Fetch the BucketInstance @@ -119,6 +139,24 @@ async def fetch_async(self) -> "BucketInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, max: Union[int, object] = values.unset, @@ -155,6 +193,42 @@ async def update_async( interval=interval, ) + def update_with_http_info( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + max=max, + interval=interval, + ) + + async def update_with_http_info_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + max=max, + interval=interval, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -192,6 +266,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BucketInstance @@ -199,10 +287,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -211,27 +321,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> BucketInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the BucketInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched BucketInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + :returns: The fetched BucketInstance + """ + payload, _, _ = self._fetch() return BucketInstance( self._version, payload, @@ -240,22 +366,47 @@ def fetch(self) -> BucketInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> BucketInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the BucketInstance + Fetch the BucketInstance and return response metadata - :returns: The fetched BucketInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> BucketInstance: + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + payload, _, _ = await self._fetch_async() return BucketInstance( self._version, payload, @@ -264,18 +415,33 @@ async def fetch_async(self) -> BucketInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, max: Union[int, object] = values.unset, interval: Union[int, object] = values.unset, - ) -> BucketInstance: + ) -> tuple: """ - Update the BucketInstance + Internal helper for update operation - :param max: Maximum number of requests permitted in during the interval. - :param interval: Number of seconds that the rate limit will be enforced over. - - :returns: The updated BucketInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -290,10 +456,24 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + payload, _, _ = self._update(max=max, interval=interval) return BucketInstance( self._version, payload, @@ -302,18 +482,39 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, max: Union[int, object] = values.unset, interval: Union[int, object] = values.unset, - ) -> BucketInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the BucketInstance + Update the BucketInstance and return response metadata :param max: Maximum number of requests permitted in during the interval. :param interval: Number of seconds that the rate limit will be enforced over. - :returns: The updated BucketInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(max=max, interval=interval) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -328,10 +529,24 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + payload, _, _ = await self._update_async(max=max, interval=interval) return BucketInstance( self._version, payload, @@ -340,6 +555,31 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance and return response metadata + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + max=max, interval=interval + ) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -358,6 +598,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: :param payload: Payload response from the API """ + return BucketInstance( self._version, payload, @@ -398,14 +639,12 @@ def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): ) ) - def create(self, max: int, interval: int) -> BucketInstance: + def _create(self, max: int, interval: int) -> tuple: """ - Create the BucketInstance - - :param max: Maximum number of requests permitted in during the interval. - :param interval: Number of seconds that the rate limit will be enforced over. + Internal helper for create operation - :returns: The created BucketInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -420,10 +659,20 @@ def create(self, max: int, interval: int) -> BucketInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, max: int, interval: int) -> BucketInstance: + """ + Create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + payload, _, _ = self._create(max=max, interval=interval) return BucketInstance( self._version, payload, @@ -431,14 +680,30 @@ def create(self, max: int, interval: int) -> BucketInstance: rate_limit_sid=self._solution["rate_limit_sid"], ) - async def create_async(self, max: int, interval: int) -> BucketInstance: + def create_with_http_info(self, max: int, interval: int) -> ApiResponse: """ - Asynchronously create the BucketInstance + Create the BucketInstance and return response metadata :param max: Maximum number of requests permitted in during the interval. :param interval: Number of seconds that the rate limit will be enforced over. - :returns: The created BucketInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(max=max, interval=interval) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, max: int, interval: int) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -453,10 +718,20 @@ async def create_async(self, max: int, interval: int) -> BucketInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, max: int, interval: int) -> BucketInstance: + """ + Asynchronously create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + payload, _, _ = await self._create_async(max=max, interval=interval) return BucketInstance( self._version, payload, @@ -464,6 +739,26 @@ async def create_async(self, max: int, interval: int) -> BucketInstance: rate_limit_sid=self._solution["rate_limit_sid"], ) + async def create_with_http_info_async(self, max: int, interval: int) -> ApiResponse: + """ + Asynchronously create the BucketInstance and return response metadata + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + max=max, interval=interval + ) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -514,6 +809,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BucketInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BucketInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -533,6 +878,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -559,6 +905,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -567,6 +914,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BucketInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BucketInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -598,7 +995,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return BucketPage(self._version, response, self._solution) + return BucketPage(self._version, response, solution=self._solution) async def page_async( self, @@ -631,7 +1028,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return BucketPage(self._version, response, self._solution) + return BucketPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BucketPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = BucketPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with BucketPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = BucketPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> BucketPage: """ @@ -643,7 +1110,7 @@ def get_page(self, target_url: str) -> BucketPage: :returns: Page of BucketInstance """ response = self._version.domain.twilio.request("GET", target_url) - return BucketPage(self._version, response, self._solution) + return BucketPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> BucketPage: """ @@ -655,7 +1122,7 @@ async def get_page_async(self, target_url: str) -> BucketPage: :returns: Page of BucketInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return BucketPage(self._version, response, self._solution) + return BucketPage(self._version, response, solution=self._solution) def get(self, sid: str) -> BucketContext: """ diff --git a/twilio/rest/verify/v2/service/verification.py b/twilio/rest/verify/v2/service/verification.py index 64988a5983..88ae5cb750 100644 --- a/twilio/rest/verify/v2/service/verification.py +++ b/twilio/rest/verify/v2/service/verification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -91,6 +92,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[VerificationContext] = None @property @@ -127,6 +129,24 @@ async def fetch_async(self) -> "VerificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": """ Update the VerificationInstance @@ -153,6 +173,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Update the VerificationInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VerificationInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -184,20 +232,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) - def fetch(self) -> VerificationInstance: + def _fetch(self) -> tuple: """ - Fetch the VerificationInstance + Internal helper for fetch operation - - :returns: The fetched VerificationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VerificationInstance: + """ + Fetch the VerificationInstance + + :returns: The fetched VerificationInstance + """ + payload, _, _ = self._fetch() return VerificationInstance( self._version, payload, @@ -205,22 +263,46 @@ def fetch(self) -> VerificationInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> VerificationInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the VerificationInstance + Fetch the VerificationInstance and return response metadata - :returns: The fetched VerificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> VerificationInstance: + """ + Asynchronous coroutine to fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + payload, _, _ = await self._fetch_async() return VerificationInstance( self._version, payload, @@ -228,13 +310,28 @@ async def fetch_async(self) -> VerificationInstance: sid=self._solution["sid"], ) - def update(self, status: "VerificationInstance.Status") -> VerificationInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the VerificationInstance + Asynchronous coroutine to fetch the VerificationInstance and return response metadata - :param status: - :returns: The updated VerificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, status: "VerificationInstance.Status") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -248,10 +345,19 @@ def update(self, status: "VerificationInstance.Status") -> VerificationInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "VerificationInstance.Status") -> VerificationInstance: + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + payload, _, _ = self._update(status=status) return VerificationInstance( self._version, payload, @@ -259,15 +365,31 @@ def update(self, status: "VerificationInstance.Status") -> VerificationInstance: sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "VerificationInstance.Status" - ) -> VerificationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the VerificationInstance + Update the VerificationInstance and return response metadata :param status: - :returns: The updated VerificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "VerificationInstance.Status") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,10 +403,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: "VerificationInstance.Status" + ) -> VerificationInstance: + """ + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + payload, _, _ = await self._update_async(status=status) return VerificationInstance( self._version, payload, @@ -292,6 +425,25 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VerificationInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -320,7 +472,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Verifications".format(**self._solution) - def create( + def _create( self, to: str, channel: str, @@ -340,30 +492,12 @@ def create( enable_sna_client_token: Union[bool, object] = values.unset, risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, tags: Union[str, object] = values.unset, - ) -> VerificationInstance: + ) -> tuple: """ - Create the VerificationInstance + Internal helper for create operation - :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. - :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message - :param custom_message: The text of a custom message to use for the verification. - :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). - :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). - :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. - :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. - :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. - :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. - :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. - :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. - :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. - :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. - :param risk_check: - :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. - - :returns: The created VerificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -396,15 +530,80 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification [DEPRECATED]. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: The created VerificationInstance + """ + payload, _, _ = self._create( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) return VerificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, channel: str, @@ -424,14 +623,14 @@ async def create_async( enable_sna_client_token: Union[bool, object] = values.unset, risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, tags: Union[str, object] = values.unset, - ) -> VerificationInstance: + ) -> ApiResponse: """ - Asynchronously create the VerificationInstance + Create the VerificationInstance and return response metadata :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message - :param custom_message: The text of a custom message to use for the verification. + :param custom_message: The text of a custom message to use for the verification [DEPRECATED]. :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. @@ -445,9 +644,61 @@ async def create_async( :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. :param risk_check: - :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + instance = VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The created VerificationInstance + async def _create_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -480,14 +731,149 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Asynchronously create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification [DEPRECATED]. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: The created VerificationInstance + """ + payload, _, _ = await self._create_async( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) return VerificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the VerificationInstance and return response metadata + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification [DEPRECATED]. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + instance = VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> VerificationContext: """ Constructs a VerificationContext diff --git a/twilio/rest/verify/v2/service/verification_check.py b/twilio/rest/verify/v2/service/verification_check.py index c09057ebe1..b80c8d6d46 100644 --- a/twilio/rest/verify/v2/service/verification_check.py +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,7 +102,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) - def create( + def _create( self, code: Union[str, object] = values.unset, to: Union[str, object] = values.unset, @@ -109,18 +110,12 @@ def create( amount: Union[str, object] = values.unset, payee: Union[str, object] = values.unset, sna_client_token: Union[str, object] = values.unset, - ) -> VerificationCheckInstance: + ) -> tuple: """ - Create the VerificationCheckInstance - - :param code: The 4-10 character string being verified. - :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. - :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + Internal helper for create operation - :returns: The created VerificationCheckInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -139,15 +134,44 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + payload, _, _ = self._create( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) return VerificationCheckInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, code: Union[str, object] = values.unset, to: Union[str, object] = values.unset, @@ -155,9 +179,9 @@ async def create_async( amount: Union[str, object] = values.unset, payee: Union[str, object] = values.unset, sna_client_token: Union[str, object] = values.unset, - ) -> VerificationCheckInstance: + ) -> ApiResponse: """ - Asynchronously create the VerificationCheckInstance + Create the VerificationCheckInstance and return response metadata :param code: The 4-10 character string being verified. :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). @@ -166,7 +190,35 @@ async def create_async( :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. - :returns: The created VerificationCheckInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + instance = VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -185,14 +237,77 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Asynchronously create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + payload, _, _ = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) return VerificationCheckInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the VerificationCheckInstance and return response metadata + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + instance = VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/verify/v2/service/webhook.py b/twilio/rest/verify/v2/service/webhook.py index dd68cf301b..2e59c8c4bb 100644 --- a/twilio/rest/verify/v2/service/webhook.py +++ b/twilio/rest/verify/v2/service/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -137,13 +157,31 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> "WebhookInstance": """ Update the WebhookInstance @@ -152,7 +190,7 @@ def update( :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: :returns: The updated WebhookInstance """ @@ -161,7 +199,7 @@ def update( event_types=event_types, webhook_url=webhook_url, status=status, - version=version, + resource_version=resource_version, ) async def update_async( @@ -170,7 +208,7 @@ async def update_async( event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> "WebhookInstance": """ Asynchronous coroutine to update the WebhookInstance @@ -179,7 +217,7 @@ async def update_async( :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: :returns: The updated WebhookInstance """ @@ -188,7 +226,61 @@ async def update_async( event_types=event_types, webhook_url=webhook_url, status=status, - version=version, + resource_version=resource_version, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, ) def __repr__(self) -> str: @@ -220,6 +312,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -227,10 +333,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -239,27 +367,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> WebhookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the WebhookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() return WebhookInstance( self._version, payload, @@ -267,22 +411,46 @@ def fetch(self) -> WebhookInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> WebhookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the WebhookInstance + Fetch the WebhookInstance and return response metadata - :returns: The fetched WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = await self._fetch_async() return WebhookInstance( self._version, payload, @@ -290,24 +458,35 @@ async def fetch_async(self) -> WebhookInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: """ - Update the WebhookInstance - - :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** - :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` - :param webhook_url: The URL associated with this Webhook. - :param status: - :param version: + Internal helper for update operation - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -316,7 +495,7 @@ def update( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({}) @@ -325,10 +504,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, @@ -336,24 +541,53 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to update the WebhookInstance + Update the WebhookInstance and return response metadata :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: - :returns: The updated WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -362,7 +596,7 @@ async def update_async( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({}) @@ -371,10 +605,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The updated WebhookInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, @@ -382,6 +642,40 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -400,6 +694,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -431,24 +726,19 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) - def create( + def _create( self, friendly_name: str, event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: """ - Create the WebhookInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** - :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` - :param webhook_url: The URL associated with this Webhook. - :param status: - :param version: - - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -457,7 +747,7 @@ def create( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -466,32 +756,84 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -500,7 +842,7 @@ async def create_async( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -509,14 +851,71 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -567,6 +966,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -586,6 +1035,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -612,6 +1062,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -620,6 +1071,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists WebhookInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -651,7 +1152,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -684,7 +1185,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with WebhookPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = WebhookPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> WebhookPage: """ @@ -696,7 +1267,7 @@ def get_page(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> WebhookPage: """ @@ -708,7 +1279,7 @@ async def get_page_async(self, target_url: str) -> WebhookPage: :returns: Page of WebhookInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) + return WebhookPage(self._version, response, solution=self._solution) def get(self, sid: str) -> WebhookContext: """ diff --git a/twilio/rest/verify/v2/template.py b/twilio/rest/verify/v2/template.py index 5a242c153e..4dfecf8f57 100644 --- a/twilio/rest/verify/v2/template.py +++ b/twilio/rest/verify/v2/template.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TemplateInstance: :param payload: Payload response from the API """ + return TemplateInstance(self._version, payload) def __repr__(self) -> str: @@ -137,6 +139,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -158,6 +216,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -187,6 +246,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -196,6 +256,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -268,6 +384,82 @@ async def page_async( ) return TemplatePage(self._version, response) + def page_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TemplatePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TemplatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TemplatePage, status code, and headers + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TemplatePage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TemplatePage: """ Retrieve a specific page of TemplateInstance records from the API. diff --git a/twilio/rest/verify/v2/verification_attempt.py b/twilio/rest/verify/v2/verification_attempt.py index 5c6989348a..4704ee828a 100644 --- a/twilio/rest/verify/v2/verification_attempt.py +++ b/twilio/rest/verify/v2/verification_attempt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,7 @@ class Channels(object): CALL = "call" EMAIL = "email" WHATSAPP = "whatsapp" + RBM = "rbm" class ConversionStatus(object): CONVERTED = "converted" @@ -76,6 +78,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[VerificationAttemptContext] = None @property @@ -111,6 +114,24 @@ async def fetch_async(self) -> "VerificationAttemptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,48 +159,96 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Attempts/{sid}".format(**self._solution) - def fetch(self) -> VerificationAttemptInstance: + def _fetch(self) -> tuple: """ - Fetch the VerificationAttemptInstance - + Internal helper for fetch operation - :returns: The fetched VerificationAttemptInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> VerificationAttemptInstance: + """ + Fetch the VerificationAttemptInstance + + :returns: The fetched VerificationAttemptInstance + """ + payload, _, _ = self._fetch() return VerificationAttemptInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> VerificationAttemptInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the VerificationAttemptInstance + Fetch the VerificationAttemptInstance and return response metadata - :returns: The fetched VerificationAttemptInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> VerificationAttemptInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + payload, _, _ = await self._fetch_async() return VerificationAttemptInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +267,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VerificationAttemptInstance: :param payload: Payload response from the API """ + return VerificationAttemptInstance(self._version, payload) def __repr__(self) -> str: @@ -247,7 +317,7 @@ def stream( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -300,7 +370,7 @@ async def stream_async( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -328,6 +398,110 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VerificationAttemptInstance and returns headers from first page + + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VerificationAttemptInstance and returns headers from first page + + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, date_created_after: Union[datetime, object] = values.unset, @@ -352,7 +526,7 @@ def list( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -365,6 +539,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_after=date_created_after, @@ -404,7 +579,7 @@ async def list_async( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -417,6 +592,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -433,6 +609,108 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VerificationAttemptInstance and returns headers from first page + + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VerificationAttemptInstance and returns headers from first page + + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, date_created_after: Union[datetime, object] = values.unset, @@ -457,7 +735,7 @@ def page( :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param channel_data_to: Destination of a verification. It is phone number in E.164 format. :param country: Filter used to query Verification Attempts sent to the specified destination country. - :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param channel: Filter used to query Verification Attempts by communication channel. :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -516,7 +794,7 @@ async def page_async( :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param channel_data_to: Destination of a verification. It is phone number in E.164 format. :param country: Filter used to query Verification Attempts sent to the specified destination country. - :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param channel: Filter used to query Verification Attempts by communication channel. :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -551,6 +829,128 @@ async def page_async( ) return VerificationAttemptPage(self._version, response) + def page_with_http_info( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VerificationAttemptPage, status code, and headers + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = VerificationAttemptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with VerificationAttemptPage, status code, and headers + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = VerificationAttemptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> VerificationAttemptPage: """ Retrieve a specific page of VerificationAttemptInstance records from the API. diff --git a/twilio/rest/verify/v2/verification_attempts_summary.py b/twilio/rest/verify/v2/verification_attempts_summary.py index 429e9f70bc..0f226478b5 100644 --- a/twilio/rest/verify/v2/verification_attempts_summary.py +++ b/twilio/rest/verify/v2/verification_attempts_summary.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class Channels(object): CALL = "call" EMAIL = "email" WHATSAPP = "whatsapp" + RBM = "rbm" """ :ivar total_attempts: Total of attempts made according to the provided filters @@ -49,8 +51,8 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.total_unconverted: Optional[int] = deserialize.integer( payload.get("total_unconverted") ) - self.conversion_rate_percentage: Optional[float] = deserialize.decimal( - payload.get("conversion_rate_percentage") + self.conversion_rate_percentage: Optional[str] = payload.get( + "conversion_rate_percentage" ) self.url: Optional[str] = payload.get("url") @@ -88,7 +90,7 @@ def fetch( :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. :returns: The fetched VerificationAttemptsSummaryInstance @@ -120,7 +122,7 @@ async def fetch_async( :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. :returns: The fetched VerificationAttemptsSummaryInstance @@ -134,6 +136,70 @@ async def fetch_async( destination_prefix=destination_prefix, ) + def fetch_with_http_info( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the VerificationAttemptsSummaryInstance with HTTP info + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + async def fetch_with_http_info_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance with HTTP info + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,7 +222,7 @@ def __init__(self, version: Version): self._uri = "/Attempts/Summary" - def fetch( + def _fetch( self, verify_service_sid: Union[str, object] = values.unset, date_created_after: Union[datetime, object] = values.unset, @@ -166,21 +232,15 @@ def fetch( "VerificationAttemptsSummaryInstance.Channels", object ] = values.unset, destination_prefix: Union[str, object] = values.unset, - ) -> VerificationAttemptsSummaryInstance: + ) -> tuple: """ - Fetch the VerificationAttemptsSummaryInstance + Internal helper for fetch operation - :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. - :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. - :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` - :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. - - :returns: The fetched VerificationAttemptsSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "VerifyServiceSid": verify_service_sid, "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), @@ -195,16 +255,47 @@ def fetch( headers["Accept"] = "application/json" - payload = self._version.fetch( - method="GET", uri=self._uri, params=data, headers=headers + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers ) + def fetch( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + payload, _, _ = self._fetch( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) return VerificationAttemptsSummaryInstance( self._version, payload, ) - async def fetch_async( + def fetch_with_http_info( self, verify_service_sid: Union[str, object] = values.unset, date_created_after: Union[datetime, object] = values.unset, @@ -214,21 +305,52 @@ async def fetch_async( "VerificationAttemptsSummaryInstance.Channels", object ] = values.unset, destination_prefix: Union[str, object] = values.unset, - ) -> VerificationAttemptsSummaryInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + Fetch the VerificationAttemptsSummaryInstance and return response metadata :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. - :returns: The fetched VerificationAttemptsSummaryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + instance = VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "VerifyServiceSid": verify_service_sid, "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), @@ -243,15 +365,83 @@ async def fetch_async( headers["Accept"] = "application/json" - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data, headers=headers + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers ) + async def fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + payload, _, _ = await self._fetch_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) return VerificationAttemptsSummaryInstance( self._version, payload, ) + async def fetch_with_http_info_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance and return response metadata + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + instance = VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/composition.py b/twilio/rest/video/v1/composition.py index 06f4d05f5f..47bb8a9641 100644 --- a/twilio/rest/video/v1/composition.py +++ b/twilio/rest/video/v1/composition.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CompositionContext] = None @property @@ -136,6 +138,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CompositionInstance": """ Fetch the CompositionInstance @@ -154,6 +174,24 @@ async def fetch_async(self) -> "CompositionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +219,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Compositions/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CompositionInstance @@ -188,10 +240,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -200,55 +274,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CompositionInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CompositionInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CompositionInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CompositionInstance: + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + payload, _, _ = self._fetch() return CompositionInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CompositionInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CompositionInstance + Fetch the CompositionInstance and return response metadata - :returns: The fetched CompositionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CompositionInstance: + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + payload, _, _ = await self._fetch_async() return CompositionInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -267,6 +395,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CompositionInstance: :param payload: Payload response from the API """ + return CompositionInstance(self._version, payload) def __repr__(self) -> str: @@ -291,7 +420,7 @@ def __init__(self, version: Version): self._uri = "/Compositions" - def create( + def _create( self, room_sid: str, video_layout: Union[object, object] = values.unset, @@ -302,21 +431,12 @@ def create( status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, trim: Union[bool, object] = values.unset, - ) -> CompositionInstance: + ) -> tuple: """ - Create the CompositionInstance + Internal helper for create operation - :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. - :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request - :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request - :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. - :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param format: - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. - :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - - :returns: The created CompositionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -340,13 +460,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CompositionInstance(self._version, payload) - - async def create_async( + def create( self, room_sid: str, video_layout: Union[object, object] = values.unset, @@ -359,7 +477,7 @@ async def create_async( trim: Union[bool, object] = values.unset, ) -> CompositionInstance: """ - Asynchronously create the CompositionInstance + Create the CompositionInstance :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request @@ -373,6 +491,78 @@ async def create_async( :returns: The created CompositionInstance """ + payload, _, _ = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionInstance(self._version, payload) + + def create_with_http_info( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionInstance and return response metadata + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -395,12 +585,91 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Asynchronously create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + payload, _, _ = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) return CompositionInstance(self._version, payload) + async def create_with_http_info_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CompositionInstance and return response metadata + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["CompositionInstance.Status", object] = values.unset, @@ -479,6 +748,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CompositionInstance and returns headers from first page + + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CompositionInstance and returns headers from first page + + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["CompositionInstance.Status", object] = values.unset, @@ -506,6 +851,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -544,6 +890,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -556,6 +903,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CompositionInstance and returns headers from first page + + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CompositionInstance and returns headers from first page + + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["CompositionInstance.Status", object] = values.unset, @@ -646,6 +1067,100 @@ async def page_async( ) return CompositionPage(self._version, response) + def page_with_http_info( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CompositionPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CompositionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CompositionPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CompositionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CompositionPage: """ Retrieve a specific page of CompositionInstance records from the API. diff --git a/twilio/rest/video/v1/composition_hook.py b/twilio/rest/video/v1/composition_hook.py index 30fead17b0..16e7cb6f4a 100644 --- a/twilio/rest/video/v1/composition_hook.py +++ b/twilio/rest/video/v1/composition_hook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CompositionHookContext] = None @property @@ -113,6 +115,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CompositionHookInstance": """ Fetch the CompositionHookInstance @@ -131,6 +151,24 @@ async def fetch_async(self) -> "CompositionHookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: str, @@ -215,6 +253,90 @@ async def update_async( status_callback_method=status_callback_method, ) + def update_with_http_info( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CompositionHookInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CompositionHookInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -242,6 +364,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/CompositionHooks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CompositionHookInstance @@ -249,10 +385,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionHookInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -261,56 +419,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionHookInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CompositionHookInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CompositionHookInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CompositionHookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionHookInstance: + """ + Fetch the CompositionHookInstance + + :returns: The fetched CompositionHookInstance + """ + payload, _, _ = self._fetch() return CompositionHookInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CompositionHookInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CompositionHookInstance + Fetch the CompositionHookInstance and return response metadata - :returns: The fetched CompositionHookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CompositionHookInstance: + """ + Asynchronous coroutine to fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + payload, _, _ = await self._fetch_async() return CompositionHookInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionHookInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -322,22 +534,12 @@ def update( resolution: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> CompositionHookInstance: + ) -> tuple: """ - Update the CompositionHookInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. - :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. - :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. - :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. - :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param format: - :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + Internal helper for update operation - :returns: The updated CompositionHookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -362,15 +564,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) return CompositionHookInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -382,9 +625,9 @@ async def update_async( resolution: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> CompositionHookInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the CompositionHookInstance + Update the CompositionHookInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. @@ -397,7 +640,43 @@ async def update_async( :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. - :returns: The updated CompositionHookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,20 +701,107 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return CompositionHookInstance( - self._version, payload, sid=self._solution["sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ + async def update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronous coroutine to update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CompositionHookInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "<Twilio.Video.V1.CompositionHookContext {}>".format(context) @@ -448,6 +814,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: :param payload: Payload response from the API """ + return CompositionHookInstance(self._version, payload) def __repr__(self) -> str: @@ -472,7 +839,7 @@ def __init__(self, version: Version): self._uri = "/CompositionHooks" - def create( + def _create( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -484,22 +851,12 @@ def create( status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, trim: Union[bool, object] = values.unset, - ) -> CompositionHookInstance: + ) -> tuple: """ - Create the CompositionHookInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. - :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. - :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. - :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. - :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param format: - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. - :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + Internal helper for create operation - :returns: The created CompositionHookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -524,13 +881,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CompositionHookInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -544,7 +899,7 @@ async def create_async( trim: Union[bool, object] = values.unset, ) -> CompositionHookInstance: """ - Asynchronously create the CompositionHookInstance + Create the CompositionHookInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. @@ -559,6 +914,83 @@ async def create_async( :returns: The created CompositionHookInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionHookInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionHookInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -582,12 +1014,97 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronously create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) return CompositionHookInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CompositionHookInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, enabled: Union[bool, object] = values.unset, @@ -666,6 +1183,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CompositionHookInstance and returns headers from first page + + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CompositionHookInstance and returns headers from first page + + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, enabled: Union[bool, object] = values.unset, @@ -693,6 +1286,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( enabled=enabled, @@ -731,6 +1325,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -743,6 +1338,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CompositionHookInstance and returns headers from first page + + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CompositionHookInstance and returns headers from first page + + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, enabled: Union[bool, object] = values.unset, @@ -833,6 +1502,100 @@ async def page_async( ) return CompositionHookPage(self._version, response) + def page_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CompositionHookPage, status code, and headers + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CompositionHookPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CompositionHookPage, status code, and headers + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CompositionHookPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CompositionHookPage: """ Retrieve a specific page of CompositionHookInstance records from the API. diff --git a/twilio/rest/video/v1/composition_settings.py b/twilio/rest/video/v1/composition_settings.py index 384ae692e8..ec04358b3d 100644 --- a/twilio/rest/video/v1/composition_settings.py +++ b/twilio/rest/video/v1/composition_settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -120,6 +121,66 @@ async def create_async( encryption_enabled=encryption_enabled, ) + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the CompositionSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "CompositionSettingsInstance": """ Fetch the CompositionSettingsInstance @@ -138,6 +199,24 @@ async def fetch_async(self) -> "CompositionSettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -160,6 +239,42 @@ def __init__(self, version: Version): self._uri = "/CompositionSettings/Default" + def _create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, friendly_name: str, @@ -181,6 +296,64 @@ def create( :returns: The created CompositionSettingsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + return CompositionSettingsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionSettingsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = CompositionSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -191,10 +364,15 @@ def create( "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), } ) + headers = values.of({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CompositionSettingsInstance(self._version, payload) + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, @@ -217,63 +395,134 @@ async def create_async( :returns: The created CompositionSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), - "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, ) + return CompositionSettingsInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the CompositionSettingsInstance and return response metadata - return CompositionSettingsInstance(self._version, payload) + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. - def fetch(self) -> CompositionSettingsInstance: + :returns: ApiResponse with instance, status code, and headers """ - Fetch the CompositionSettingsInstance + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = CompositionSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CompositionSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> CompositionSettingsInstance: + """ + Fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + payload, _, _ = self._fetch() return CompositionSettingsInstance( self._version, payload, ) - async def fetch_async(self) -> CompositionSettingsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CompositionSettingsInstance + Fetch the CompositionSettingsInstance and return response metadata - :returns: The fetched CompositionSettingsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CompositionSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CompositionSettingsInstance: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + payload, _, _ = await self._fetch_async() return CompositionSettingsInstance( self._version, payload, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CompositionSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/recording.py b/twilio/rest/video/v1/recording.py index f474345fe0..f99a8322dd 100644 --- a/twilio/rest/video/v1/recording.py +++ b/twilio/rest/video/v1/recording.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -136,6 +138,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -154,6 +174,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +219,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Recordings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -188,10 +240,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -200,55 +274,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RecordingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RecordingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() return RecordingInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> RecordingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() return RecordingInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -267,6 +395,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance(self._version, payload) def __repr__(self) -> str: @@ -381,6 +510,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RecordingInstance and returns headers from first page + + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RecordingInstance and returns headers from first page + + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["RecordingInstance.Status", object] = values.unset, @@ -412,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -456,6 +674,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -470,6 +689,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RecordingInstance and returns headers from first page + + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RecordingInstance and returns headers from first page + + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["RecordingInstance.Status", object] = values.unset, @@ -572,6 +877,112 @@ async def page_async( ) return RecordingPage(self._version, response) + def page_with_http_info( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RecordingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RecordingPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RecordingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RecordingPage: """ Retrieve a specific page of RecordingInstance records from the API. diff --git a/twilio/rest/video/v1/recording_settings.py b/twilio/rest/video/v1/recording_settings.py index 46259b6cf8..ce2373eb9f 100644 --- a/twilio/rest/video/v1/recording_settings.py +++ b/twilio/rest/video/v1/recording_settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -120,6 +121,66 @@ async def create_async( encryption_enabled=encryption_enabled, ) + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the RecordingSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "RecordingSettingsInstance": """ Fetch the RecordingSettingsInstance @@ -138,6 +199,24 @@ async def fetch_async(self) -> "RecordingSettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -160,6 +239,42 @@ def __init__(self, version: Version): self._uri = "/RecordingSettings/Default" + def _create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, friendly_name: str, @@ -181,6 +296,64 @@ def create( :returns: The created RecordingSettingsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + return RecordingSettingsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingSettingsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = RecordingSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -191,10 +364,15 @@ def create( "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), } ) + headers = values.of({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RecordingSettingsInstance(self._version, payload) + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, @@ -217,63 +395,134 @@ async def create_async( :returns: The created RecordingSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), - "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, ) + return RecordingSettingsInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the RecordingSettingsInstance and return response metadata - return RecordingSettingsInstance(self._version, payload) + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. - def fetch(self) -> RecordingSettingsInstance: + :returns: ApiResponse with instance, status code, and headers """ - Fetch the RecordingSettingsInstance + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = RecordingSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RecordingSettingsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> RecordingSettingsInstance: + """ + Fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + payload, _, _ = self._fetch() return RecordingSettingsInstance( self._version, payload, ) - async def fetch_async(self) -> RecordingSettingsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingSettingsInstance + Fetch the RecordingSettingsInstance and return response metadata - :returns: The fetched RecordingSettingsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingSettingsInstance: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + payload, _, _ = await self._fetch_async() return RecordingSettingsInstance( self._version, payload, ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingSettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/room/__init__.py b/twilio/rest/video/v1/room/__init__.py index 0fb7a7b0dd..cdc626b3e3 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +24,7 @@ from twilio.rest.video.v1.room.participant import ParticipantList from twilio.rest.video.v1.room.recording_rules import RecordingRulesList from twilio.rest.video.v1.room.room_recording import RoomRecordingList +from twilio.rest.video.v1.room.transcriptions import TranscriptionsList class RoomInstance(InstanceResource): @@ -33,9 +35,9 @@ class RoomStatus(object): FAILED = "failed" class RoomType(object): + GROUP = "group" GO = "go" PEER_TO_PEER = "peer-to-peer" - GROUP = "group" GROUP_SMALL = "group-small" class VideoCodec(object): @@ -124,6 +126,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RoomContext] = None @property @@ -159,6 +162,24 @@ async def fetch_async(self) -> "RoomInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": """ Update the RoomInstance @@ -183,6 +204,32 @@ async def update_async(self, status: "RoomInstance.RoomStatus") -> "RoomInstance status=status, ) + def update_with_http_info(self, status: "RoomInstance.RoomStatus") -> ApiResponse: + """ + Update the RoomInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "RoomInstance.RoomStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RoomInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def participants(self) -> ParticipantList: """ @@ -204,6 +251,13 @@ def recordings(self) -> RoomRecordingList: """ return self._proxy.recordings + @property + def transcriptions(self) -> TranscriptionsList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + def __repr__(self) -> str: """ Provide a friendly representation @@ -234,56 +288,104 @@ def __init__(self, version: Version, sid: str): self._participants: Optional[ParticipantList] = None self._recording_rules: Optional[RecordingRulesList] = None self._recordings: Optional[RoomRecordingList] = None + self._transcriptions: Optional[TranscriptionsList] = None - def fetch(self) -> RoomInstance: + def _fetch(self) -> tuple: """ - Fetch the RoomInstance + Internal helper for fetch operation - - :returns: The fetched RoomInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + payload, _, _ = self._fetch() return RoomInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> RoomInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoomInstance + Fetch the RoomInstance and return response metadata - :returns: The fetched RoomInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + payload, _, _ = await self._fetch_async() return RoomInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RoomInstance + Asynchronous coroutine to fetch the RoomInstance and return response metadata - :param status: - :returns: The updated RoomInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, status: "RoomInstance.RoomStatus") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -297,19 +399,39 @@ def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + payload, _, _ = self._update(status=status) return RoomInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + def update_with_http_info(self, status: "RoomInstance.RoomStatus") -> ApiResponse: """ - Asynchronous coroutine to update the RoomInstance + Update the RoomInstance and return response metadata :param status: - :returns: The updated RoomInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = RoomInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, status: "RoomInstance.RoomStatus") -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -323,12 +445,35 @@ async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + payload, _, _ = await self._update_async(status=status) return RoomInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, status: "RoomInstance.RoomStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RoomInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = RoomInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def participants(self) -> ParticipantList: """ @@ -365,6 +510,18 @@ def recordings(self) -> RoomRecordingList: ) return self._recordings + @property + def transcriptions(self) -> TranscriptionsList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionsList( + self._version, + self._solution["sid"], + ) + return self._transcriptions + def __repr__(self) -> str: """ Provide a friendly representation @@ -383,6 +540,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -407,7 +565,7 @@ def __init__(self, version: Version): self._uri = "/Rooms" - def create( + def _create( self, enable_turn: Union[bool, object] = values.unset, type: Union["RoomInstance.RoomType", object] = values.unset, @@ -416,35 +574,22 @@ def create( status_callback_method: Union[str, object] = values.unset, max_participants: Union[int, object] = values.unset, record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, media_region: Union[str, object] = values.unset, recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, audio_only: Union[bool, object] = values.unset, max_participant_duration: Union[int, object] = values.unset, empty_room_timeout: Union[int, object] = values.unset, unused_room_timeout: Union[int, object] = values.unset, large_room: Union[bool, object] = values.unset, - ) -> RoomInstance: + ) -> tuple: """ - Create the RoomInstance + Internal helper for create operation - :param enable_turn: Deprecated, now always considered to be true. - :param type: - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. - :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. - :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. - :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. - :param record_participants_on_connect: Whether to start recording when Participants connect. - :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. - :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). - :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording - :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. - :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). - :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). - :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). - :param large_room: When set to true, indicated that this is the large room. - - :returns: The created RoomInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -458,9 +603,15 @@ def create( "RecordParticipantsOnConnect": serialize.boolean_to_string( record_participants_on_connect ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), "VideoCodecs": serialize.map(video_codecs, lambda e: e), "MediaRegion": media_region, "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, @@ -474,13 +625,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RoomInstance(self._version, payload) - - async def create_async( + def create( self, enable_turn: Union[bool, object] = values.unset, type: Union["RoomInstance.RoomType", object] = values.unset, @@ -489,9 +638,11 @@ async def create_async( status_callback_method: Union[str, object] = values.unset, max_participants: Union[int, object] = values.unset, record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, media_region: Union[str, object] = values.unset, recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, audio_only: Union[bool, object] = values.unset, max_participant_duration: Union[int, object] = values.unset, empty_room_timeout: Union[int, object] = values.unset, @@ -499,7 +650,7 @@ async def create_async( large_room: Union[bool, object] = values.unset, ) -> RoomInstance: """ - Asynchronously create the RoomInstance + Create the RoomInstance :param enable_turn: Deprecated, now always considered to be true. :param type: @@ -508,9 +659,11 @@ async def create_async( :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). @@ -519,6 +672,118 @@ async def create_async( :returns: The created RoomInstance """ + payload, _, _ = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + return RoomInstance(self._version, payload) + + def create_with_http_info( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RoomInstance and return response metadata + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + instance = RoomInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -531,9 +796,15 @@ async def create_async( "RecordParticipantsOnConnect": serialize.boolean_to_string( record_participants_on_connect ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), "VideoCodecs": serialize.map(video_codecs, lambda e: e), "MediaRegion": media_region, "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, @@ -547,12 +818,139 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Asynchronously create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance + """ + payload, _, _ = await self._create_async( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) return RoomInstance(self._version, payload) + async def create_with_http_info_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RoomInstance and return response metadata + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + instance = RoomInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["RoomInstance.RoomStatus", object] = values.unset, @@ -631,6 +1029,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoomInstance and returns headers from first page + + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoomInstance and returns headers from first page + + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["RoomInstance.RoomStatus", object] = values.unset, @@ -658,6 +1132,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -696,6 +1171,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -708,6 +1184,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoomInstance and returns headers from first page + + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoomInstance and returns headers from first page + + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["RoomInstance.RoomStatus", object] = values.unset, @@ -798,6 +1348,100 @@ async def page_async( ) return RoomPage(self._version, response) + def page_with_http_info( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RoomPage: """ Retrieve a specific page of RoomInstance records from the API. diff --git a/twilio/rest/video/v1/room/participant/__init__.py b/twilio/rest/video/v1/room/participant/__init__.py index 756a166eae..fdee154a0c 100644 --- a/twilio/rest/video/v1/room/participant/__init__.py +++ b/twilio/rest/video/v1/room/participant/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class ParticipantInstance(InstanceResource): class Status(object): CONNECTED = "connected" DISCONNECTED = "disconnected" + RECONNECTING = "reconnecting" """ :ivar sid: The unique string that we created to identify the RoomParticipant resource. @@ -81,6 +83,7 @@ def __init__( "room_sid": room_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -117,6 +120,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["ParticipantInstance.Status", object] = values.unset ) -> "ParticipantInstance": @@ -145,6 +166,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def anonymize(self) -> AnonymizeList: """ @@ -207,20 +256,30 @@ def __init__(self, version: Version, room_sid: str, sid: str): self._subscribe_rules: Optional[SubscribeRulesList] = None self._subscribed_tracks: Optional[SubscribedTrackList] = None - def fetch(self) -> ParticipantInstance: + def _fetch(self) -> tuple: """ - Fetch the ParticipantInstance + Internal helper for fetch operation - - :returns: The fetched ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() return ParticipantInstance( self._version, payload, @@ -228,22 +287,46 @@ def fetch(self) -> ParticipantInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ParticipantInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ParticipantInstance + Fetch the ParticipantInstance and return response metadata - :returns: The fetched ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = await self._fetch_async() return ParticipantInstance( self._version, payload, @@ -251,15 +334,30 @@ async def fetch_async(self) -> ParticipantInstance: sid=self._solution["sid"], ) - def update( - self, status: Union["ParticipantInstance.Status", object] = values.unset - ) -> ParticipantInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ParticipantInstance + Asynchronous coroutine to fetch the ParticipantInstance and return response metadata - :param status: - :returns: The updated ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -273,10 +371,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = self._update(status=status) return ParticipantInstance( self._version, payload, @@ -284,15 +393,33 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: Union["ParticipantInstance.Status", object] = values.unset - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ParticipantInstance + Update the ParticipantInstance and return response metadata :param status: - :returns: The updated ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -306,10 +433,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + payload, _, _ = await self._update_async(status=status) return ParticipantInstance( self._version, payload, @@ -317,6 +455,25 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def anonymize(self) -> AnonymizeList: """ @@ -387,6 +544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -496,6 +654,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantInstance and returns headers from first page + + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantInstance and returns headers from first page + + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["ParticipantInstance.Status", object] = values.unset, @@ -523,6 +757,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -561,6 +796,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -573,6 +809,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantInstance and returns headers from first page + + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantInstance and returns headers from first page + + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["ParticipantInstance.Status", object] = values.unset, @@ -616,7 +926,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def page_async( self, @@ -661,7 +971,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ParticipantPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ParticipantPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantPage: """ @@ -673,7 +1077,7 @@ def get_page(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ParticipantPage: """ @@ -685,7 +1089,7 @@ async def get_page_async(self, target_url: str) -> ParticipantPage: :returns: Page of ParticipantInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ParticipantPage(self._version, response, self._solution) + return ParticipantPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ParticipantContext: """ diff --git a/twilio/rest/video/v1/room/participant/anonymize.py b/twilio/rest/video/v1/room/participant/anonymize.py index 0560d3eff4..4a024d06a2 100644 --- a/twilio/rest/video/v1/room/participant/anonymize.py +++ b/twilio/rest/video/v1/room/participant/anonymize.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "room_sid": room_sid, "sid": sid, } + self._context: Optional[AnonymizeContext] = None @property @@ -106,6 +108,24 @@ async def update_async(self) -> "AnonymizeInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -137,12 +157,12 @@ def __init__(self, version: Version, room_sid: str, sid: str): **self._solution ) - def update(self) -> AnonymizeInstance: + def _update(self) -> tuple: """ - Update the AnonymizeInstance + Internal helper for update operation - - :returns: The updated AnonymizeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -150,10 +170,18 @@ def update(self) -> AnonymizeInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self) -> AnonymizeInstance: + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + payload, _, _ = self._update() return AnonymizeInstance( self._version, payload, @@ -161,12 +189,28 @@ def update(self) -> AnonymizeInstance: sid=self._solution["sid"], ) - async def update_async(self) -> AnonymizeInstance: + def update_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to update the AnonymizeInstance + Update the AnonymizeInstance and return response metadata - :returns: The updated AnonymizeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -174,10 +218,18 @@ async def update_async(self) -> AnonymizeInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self) -> AnonymizeInstance: + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + payload, _, _ = await self._update_async() return AnonymizeInstance( self._version, payload, @@ -185,6 +237,22 @@ async def update_async(self) -> AnonymizeInstance: sid=self._solution["sid"], ) + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AnonymizeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/room/participant/published_track.py b/twilio/rest/video/v1/room/participant/published_track.py index a766b276ab..ec1ebf09a4 100644 --- a/twilio/rest/video/v1/room/participant/published_track.py +++ b/twilio/rest/video/v1/room/participant/published_track.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[PublishedTrackContext] = None @property @@ -107,6 +109,24 @@ async def fetch_async(self) -> "PublishedTrackInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -140,20 +160,30 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: s **self._solution ) - def fetch(self) -> PublishedTrackInstance: + def _fetch(self) -> tuple: """ - Fetch the PublishedTrackInstance - + Internal helper for fetch operation - :returns: The fetched PublishedTrackInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> PublishedTrackInstance: + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + payload, _, _ = self._fetch() return PublishedTrackInstance( self._version, payload, @@ -162,22 +192,47 @@ def fetch(self) -> PublishedTrackInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> PublishedTrackInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the PublishedTrackInstance + Fetch the PublishedTrackInstance and return response metadata - :returns: The fetched PublishedTrackInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> PublishedTrackInstance: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + payload, _, _ = await self._fetch_async() return PublishedTrackInstance( self._version, payload, @@ -186,6 +241,23 @@ async def fetch_async(self) -> PublishedTrackInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -204,6 +276,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PublishedTrackInstance: :param payload: Payload response from the API """ + return PublishedTrackInstance( self._version, payload, @@ -294,6 +367,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -313,6 +436,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -339,6 +463,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -347,6 +472,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PublishedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -378,7 +553,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return PublishedTrackPage(self._version, response, self._solution) + return PublishedTrackPage(self._version, response, solution=self._solution) async def page_async( self, @@ -411,7 +586,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return PublishedTrackPage(self._version, response, self._solution) + return PublishedTrackPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublishedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PublishedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with PublishedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PublishedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> PublishedTrackPage: """ @@ -423,7 +668,7 @@ def get_page(self, target_url: str) -> PublishedTrackPage: :returns: Page of PublishedTrackInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PublishedTrackPage(self._version, response, self._solution) + return PublishedTrackPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PublishedTrackPage: """ @@ -435,7 +680,7 @@ async def get_page_async(self, target_url: str) -> PublishedTrackPage: :returns: Page of PublishedTrackInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PublishedTrackPage(self._version, response, self._solution) + return PublishedTrackPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PublishedTrackContext: """ diff --git a/twilio/rest/video/v1/room/participant/subscribe_rules.py b/twilio/rest/video/v1/room/participant/subscribe_rules.py index 992f8a374b..f13f7e6473 100644 --- a/twilio/rest/video/v1/room/participant/subscribe_rules.py +++ b/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -88,19 +89,29 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str): ) ) - def fetch(self) -> SubscribeRulesInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the SubscribeRulesInstance - + Internal helper for fetch operation - :returns: The fetched SubscribeRulesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SubscribeRulesInstance: + """ + Fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + payload, _, _ = self._fetch() return SubscribeRulesInstance( self._version, payload, @@ -108,21 +119,45 @@ def fetch(self) -> SubscribeRulesInstance: participant_sid=self._solution["participant_sid"], ) - async def fetch_async(self) -> SubscribeRulesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the SubscribeRulesInstance + Fetch the SubscribeRulesInstance and return response metadata - :returns: The fetched SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + payload, _, _ = await self._fetch_async() return SubscribeRulesInstance( self._version, payload, @@ -130,15 +165,28 @@ async def fetch_async(self) -> SubscribeRulesInstance: participant_sid=self._solution["participant_sid"], ) - def update( - self, rules: Union[object, object] = values.unset - ) -> SubscribeRulesInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SubscribeRulesInstance + Asynchronously fetch the SubscribeRulesInstance and return response metadata - :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. - :returns: The created SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -152,10 +200,21 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The updated SubscribeRulesInstance + """ + payload, _, _ = self._update(rules=rules) return SubscribeRulesInstance( self._version, payload, @@ -163,15 +222,31 @@ def update( participant_sid=self._solution["participant_sid"], ) - async def update_async( + def update_with_http_info( self, rules: Union[object, object] = values.unset - ) -> SubscribeRulesInstance: + ) -> ApiResponse: """ - Asynchronously update the SubscribeRulesInstance + Update the SubscribeRulesInstance and return response metadata :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. - :returns: The created SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(rules=rules) + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -185,10 +260,21 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Asynchronously update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The updated SubscribeRulesInstance + """ + payload, _, _ = await self._update_async(rules=rules) return SubscribeRulesInstance( self._version, payload, @@ -196,6 +282,25 @@ async def update_async( participant_sid=self._solution["participant_sid"], ) + async def update_with_http_info_async( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously update the SubscribeRulesInstance and return response metadata + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(rules=rules) + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/room/participant/subscribed_track.py b/twilio/rest/video/v1/room/participant/subscribed_track.py index 8baea148dc..de2ef19592 100644 --- a/twilio/rest/video/v1/room/participant/subscribed_track.py +++ b/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[SubscribedTrackContext] = None @property @@ -109,6 +111,24 @@ async def fetch_async(self) -> "SubscribedTrackInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,20 +162,30 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: s **self._solution ) - def fetch(self) -> SubscribedTrackInstance: + def _fetch(self) -> tuple: """ - Fetch the SubscribedTrackInstance - + Internal helper for fetch operation - :returns: The fetched SubscribedTrackInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SubscribedTrackInstance: + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + payload, _, _ = self._fetch() return SubscribedTrackInstance( self._version, payload, @@ -164,22 +194,47 @@ def fetch(self) -> SubscribedTrackInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> SubscribedTrackInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SubscribedTrackInstance + Fetch the SubscribedTrackInstance and return response metadata - :returns: The fetched SubscribedTrackInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SubscribedTrackInstance: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + payload, _, _ = await self._fetch_async() return SubscribedTrackInstance( self._version, payload, @@ -188,6 +243,23 @@ async def fetch_async(self) -> SubscribedTrackInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -206,6 +278,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscribedTrackInstance: :param payload: Payload response from the API """ + return SubscribedTrackInstance( self._version, payload, @@ -296,6 +369,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -315,6 +438,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -341,6 +465,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -349,6 +474,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SubscribedTrackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -380,7 +555,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return SubscribedTrackPage(self._version, response, self._solution) + return SubscribedTrackPage(self._version, response, solution=self._solution) async def page_async( self, @@ -413,7 +588,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return SubscribedTrackPage(self._version, response, self._solution) + return SubscribedTrackPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SubscribedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SubscribedTrackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SubscribedTrackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> SubscribedTrackPage: """ @@ -425,7 +670,7 @@ def get_page(self, target_url: str) -> SubscribedTrackPage: :returns: Page of SubscribedTrackInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SubscribedTrackPage(self._version, response, self._solution) + return SubscribedTrackPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SubscribedTrackPage: """ @@ -437,7 +682,7 @@ async def get_page_async(self, target_url: str) -> SubscribedTrackPage: :returns: Page of SubscribedTrackInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SubscribedTrackPage(self._version, response, self._solution) + return SubscribedTrackPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SubscribedTrackContext: """ diff --git a/twilio/rest/video/v1/room/recording_rules.py b/twilio/rest/video/v1/room/recording_rules.py index d79d465c28..d399cd03d4 100644 --- a/twilio/rest/video/v1/room/recording_rules.py +++ b/twilio/rest/video/v1/room/recording_rules.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,51 +74,92 @@ def __init__(self, version: Version, room_sid: str): } self._uri = "/Rooms/{room_sid}/RecordingRules".format(**self._solution) - def fetch(self) -> RecordingRulesInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the RecordingRulesInstance - + Internal helper for fetch operation - :returns: The fetched RecordingRulesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingRulesInstance: + """ + Fetch the RecordingRulesInstance + + :returns: The fetched RecordingRulesInstance + """ + payload, _, _ = self._fetch() return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) - async def fetch_async(self) -> RecordingRulesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the RecordingRulesInstance + Fetch the RecordingRulesInstance and return response metadata - :returns: The fetched RecordingRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + payload, _, _ = await self._fetch_async() return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) - def update( - self, rules: Union[object, object] = values.unset - ) -> RecordingRulesInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the RecordingRulesInstance + Asynchronously fetch the RecordingRulesInstance and return response metadata - :param rules: A JSON-encoded array of recording rules. - :returns: The created RecordingRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -131,23 +173,47 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The updated RecordingRulesInstance + """ + payload, _, _ = self._update(rules=rules) return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) - async def update_async( + def update_with_http_info( self, rules: Union[object, object] = values.unset - ) -> RecordingRulesInstance: + ) -> ApiResponse: """ - Asynchronously update the RecordingRulesInstance + Update the RecordingRulesInstance and return response metadata :param rules: A JSON-encoded array of recording rules. - :returns: The created RecordingRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(rules=rules) + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -161,14 +227,41 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Asynchronously update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The updated RecordingRulesInstance + """ + payload, _, _ = await self._update_async(rules=rules) return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) + async def update_with_http_info_async( + self, rules: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously update the RecordingRulesInstance and return response metadata + + :param rules: A JSON-encoded array of recording rules. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(rules=rules) + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/video/v1/room/room_recording.py b/twilio/rest/video/v1/room/room_recording.py index 21d433ce38..697904b713 100644 --- a/twilio/rest/video/v1/room/room_recording.py +++ b/twilio/rest/video/v1/room/room_recording.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -102,6 +103,7 @@ def __init__( "room_sid": room_sid, "sid": sid or self.sid, } + self._context: Optional[RoomRecordingContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoomRecordingInstance": """ Fetch the RoomRecordingInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "RoomRecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -185,6 +223,20 @@ def __init__(self, version: Version, room_sid: str, sid: str): } self._uri = "/Rooms/{room_sid}/Recordings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoomRecordingInstance @@ -192,10 +244,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -204,27 +278,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RoomRecordingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RoomRecordingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RoomRecordingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomRecordingInstance: + """ + Fetch the RoomRecordingInstance + + :returns: The fetched RoomRecordingInstance + """ + payload, _, _ = self._fetch() return RoomRecordingInstance( self._version, payload, @@ -232,22 +322,46 @@ def fetch(self) -> RoomRecordingInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> RoomRecordingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RoomRecordingInstance + Fetch the RoomRecordingInstance and return response metadata - :returns: The fetched RoomRecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RoomRecordingInstance: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + payload, _, _ = await self._fetch_async() return RoomRecordingInstance( self._version, payload, @@ -255,6 +369,22 @@ async def fetch_async(self) -> RoomRecordingInstance: sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -273,6 +403,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomRecordingInstance: :param payload: Payload response from the API """ + return RoomRecordingInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -382,6 +513,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RoomRecordingInstance and returns headers from first page + + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RoomRecordingInstance and returns headers from first page + + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["RoomRecordingInstance.Status", object] = values.unset, @@ -409,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -447,6 +655,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -459,6 +668,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RoomRecordingInstance and returns headers from first page + + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RoomRecordingInstance and returns headers from first page + + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["RoomRecordingInstance.Status", object] = values.unset, @@ -502,7 +785,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return RoomRecordingPage(self._version, response, self._solution) + return RoomRecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -547,7 +830,101 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return RoomRecordingPage(self._version, response, self._solution) + return RoomRecordingPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomRecordingPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RoomRecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RoomRecordingPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RoomRecordingPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> RoomRecordingPage: """ @@ -559,7 +936,7 @@ def get_page(self, target_url: str) -> RoomRecordingPage: :returns: Page of RoomRecordingInstance """ response = self._version.domain.twilio.request("GET", target_url) - return RoomRecordingPage(self._version, response, self._solution) + return RoomRecordingPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> RoomRecordingPage: """ @@ -571,7 +948,7 @@ async def get_page_async(self, target_url: str) -> RoomRecordingPage: :returns: Page of RoomRecordingInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return RoomRecordingPage(self._version, response, self._solution) + return RoomRecordingPage(self._version, response, solution=self._solution) def get(self, sid: str) -> RoomRecordingContext: """ diff --git a/twilio/rest/video/v1/room/transcriptions.py b/twilio/rest/video/v1/room/transcriptions.py new file mode 100644 index 0000000000..78ee6ceefe --- /dev/null +++ b/twilio/rest/video/v1/room/transcriptions.py @@ -0,0 +1,1033 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionsInstance(InstanceResource): + + class Status(object): + STARTED = "started" + STOPPED = "stopped" + FAILED = "failed" + + """ + :ivar ttid: The unique string that we created to identify the transcriptions resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + :ivar room_sid: The SID of the transcriptions's room. + :ivar source_sid: The SID of the transcriptions's associated call. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar start_time: The time of transcriptions connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the transcriptions disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the transcriptions were `connected`. Populated only after the transcriptions is `stopped`. + :ivar url: The absolute URL of the resource. + :ivar configuration: An JSON object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + ttid: Optional[str] = None, + ): + super().__init__(version) + + self.ttid: Optional[str] = payload.get("ttid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.status: Optional["TranscriptionsInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + + self._solution = { + "room_sid": room_sid, + "ttid": ttid or self.ttid, + } + + self._context: Optional[TranscriptionsContext] = None + + @property + def _proxy(self) -> "TranscriptionsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionsContext for this TranscriptionsInstance + """ + if self._context is None: + self._context = TranscriptionsContext( + self._version, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return self._context + + def fetch(self) -> "TranscriptionsInstance": + """ + Fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionsInstance": + """ + Asynchronous coroutine to fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> "TranscriptionsInstance": + """ + Update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + return self._proxy.update( + status=status, + configuration=configuration, + ) + + async def update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> "TranscriptionsInstance": + """ + Asynchronous coroutine to update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + return await self._proxy.update_async( + status=status, + configuration=configuration, + ) + + def update_with_http_info( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionsInstance with HTTP info + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + configuration=configuration, + ) + + async def update_with_http_info_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionsInstance with HTTP info + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + configuration=configuration, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.TranscriptionsInstance {}>".format(context) + + +class TranscriptionsContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, ttid: str): + """ + Initialize the TranscriptionsContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the transcriptions resource to update. + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "ttid": ttid, + } + self._uri = "/Rooms/{room_sid}/Transcriptions/{ttid}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionsInstance: + """ + Fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + payload, _, _ = self._fetch() + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionsInstance: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance + + + :returns: The fetched TranscriptionsInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionsInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> TranscriptionsInstance: + """ + Update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + payload, _, _ = self._update(status=status, configuration=configuration) + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + def update_with_http_info( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionsInstance and return response metadata + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> TranscriptionsInstance: + """ + Asynchronous coroutine to update the TranscriptionsInstance + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The updated TranscriptionsInstance + """ + payload, _, _ = await self._update_async( + status=status, configuration=configuration + ) + return TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + + async def update_with_http_info_async( + self, + status: Union["TranscriptionsInstance.Status", object] = values.unset, + configuration: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionsInstance and return response metadata + + :param status: + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ttid=self._solution["ttid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.TranscriptionsContext {}>".format(context) + + +class TranscriptionsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionsInstance: + """ + Build an instance of TranscriptionsInstance + + :param payload: Payload response from the API + """ + + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.TranscriptionsPage>" + + +class TranscriptionsList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the TranscriptionsList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the transcriptions resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Transcriptions".format(**self._solution) + + def _create(self, configuration: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, configuration: Union[object, object] = values.unset + ) -> TranscriptionsInstance: + """ + Create the TranscriptionsInstance + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The created TranscriptionsInstance + """ + payload, _, _ = self._create(configuration=configuration) + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def create_with_http_info( + self, configuration: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the TranscriptionsInstance and return response metadata + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(configuration=configuration) + instance = TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, configuration: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, configuration: Union[object, object] = values.unset + ) -> TranscriptionsInstance: + """ + Asynchronously create the TranscriptionsInstance + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: The created TranscriptionsInstance + """ + payload, _, _ = await self._create_async(configuration=configuration) + return TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def create_with_http_info_async( + self, configuration: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionsInstance and return response metadata + + :param configuration: A collection of properties that describe transcription behaviour. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + configuration=configuration + ) + instance = TranscriptionsInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionsInstance]: + """ + Streams TranscriptionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionsInstance]: + """ + Asynchronously streams TranscriptionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionsInstance]: + """ + Lists TranscriptionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionsInstance]: + """ + Asynchronously lists TranscriptionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptionsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionsPage: + """ + Retrieve a single page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionsPage(self._version, response, solution=self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionsPage: + """ + Asynchronously retrieve a single page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionsPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptionsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptionsPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + def get_page(self, target_url: str) -> TranscriptionsPage: + """ + Retrieve a specific page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionsPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionsPage: + """ + Asynchronously retrieve a specific page of TranscriptionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionsPage(self._version, response, solution=self._solution) + + def get(self, ttid: str) -> TranscriptionsContext: + """ + Constructs a TranscriptionsContext + + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + return TranscriptionsContext( + self._version, room_sid=self._solution["room_sid"], ttid=ttid + ) + + def __call__(self, ttid: str) -> TranscriptionsContext: + """ + Constructs a TranscriptionsContext + + :param ttid: The Twilio type id of the transcriptions resource to update. + """ + return TranscriptionsContext( + self._version, room_sid=self._solution["room_sid"], ttid=ttid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.TranscriptionsList>" diff --git a/twilio/rest/voice/VoiceBase.py b/twilio/rest/voice/VoiceBase.py index 4394ab1a2d..2485e826d0 100644 --- a/twilio/rest/voice/VoiceBase.py +++ b/twilio/rest/voice/VoiceBase.py @@ -14,6 +14,8 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.voice.v1 import V1 +from twilio.rest.voice.v2 import V2 +from twilio.rest.voice.v3 import V3 class VoiceBase(Domain): @@ -26,6 +28,8 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://voice.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -36,6 +40,24 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Voice + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Voice + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/voice/v1/archived_call.py b/twilio/rest/voice/v1/archived_call.py index 939f1a03e2..090f21d452 100644 --- a/twilio/rest/voice/v1/archived_call.py +++ b/twilio/rest/voice/v1/archived_call.py @@ -14,6 +14,7 @@ from datetime import date from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.list_resource import ListResource @@ -39,6 +40,20 @@ def __init__(self, version: Version, date: date, sid: str): } self._uri = "/Archives/{date}/Calls/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ArchivedCallInstance @@ -46,10 +61,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ArchivedCallInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -58,12 +95,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ArchivedCallInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/voice/v1/byoc_trunk.py b/twilio/rest/voice/v1/byoc_trunk.py index 304bdd78a5..f6e053c0dc 100644 --- a/twilio/rest/voice/v1/byoc_trunk.py +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ByocTrunkContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ByocTrunkInstance": """ Fetch the ByocTrunkInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "ByocTrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -208,6 +246,90 @@ async def update_async( from_domain_sid=from_domain_sid, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ByocTrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ByocTrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +357,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/ByocTrunks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ByocTrunkInstance @@ -242,10 +378,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -254,56 +412,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ByocTrunkInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ByocTrunkInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ByocTrunkInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ByocTrunkInstance: + """ + Fetch the ByocTrunkInstance + + :returns: The fetched ByocTrunkInstance + """ + payload, _, _ = self._fetch() return ByocTrunkInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ByocTrunkInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ByocTrunkInstance + Fetch the ByocTrunkInstance and return response metadata - :returns: The fetched ByocTrunkInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ByocTrunkInstance: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + payload, _, _ = await self._fetch_async() return ByocTrunkInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -315,22 +527,12 @@ def update( cnam_lookup_enabled: Union[bool, object] = values.unset, connection_policy_sid: Union[str, object] = values.unset, from_domain_sid: Union[str, object] = values.unset, - ) -> ByocTrunkInstance: + ) -> tuple: """ - Update the ByocTrunkInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param voice_url: The URL we should call when the BYOC Trunk receives a call. - :param voice_method: The HTTP method we should use to call `voice_url` - :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. - :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. - :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. - :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + Internal helper for update operation - :returns: The updated ByocTrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -353,13 +555,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -373,7 +573,7 @@ async def update_async( from_domain_sid: Union[str, object] = values.unset, ) -> ByocTrunkInstance: """ - Asynchronous coroutine to update the ByocTrunkInstance + Update the ByocTrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :param voice_url: The URL we should call when the BYOC Trunk receives a call. @@ -388,6 +588,83 @@ async def update_async( :returns: The updated ByocTrunkInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ByocTrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + instance = ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -409,22 +686,107 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "<Twilio.Voice.V1.ByocTrunkContext {}>".format(context) - - + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ByocTrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + instance = ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ByocTrunkContext {}>".format(context) + + class ByocTrunkPage(Page): def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: @@ -433,6 +795,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: :param payload: Payload response from the API """ + return ByocTrunkInstance(self._version, payload) def __repr__(self) -> str: @@ -457,7 +820,7 @@ def __init__(self, version: Version): self._uri = "/ByocTrunks" - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -469,22 +832,12 @@ def create( cnam_lookup_enabled: Union[bool, object] = values.unset, connection_policy_sid: Union[str, object] = values.unset, from_domain_sid: Union[str, object] = values.unset, - ) -> ByocTrunkInstance: + ) -> tuple: """ - Create the ByocTrunkInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param voice_url: The URL we should call when the BYOC Trunk receives a call. - :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. - :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. - :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. - :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + Internal helper for create operation - :returns: The created ByocTrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -507,13 +860,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ByocTrunkInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -527,7 +878,7 @@ async def create_async( from_domain_sid: Union[str, object] = values.unset, ) -> ByocTrunkInstance: """ - Asynchronously create the ByocTrunkInstance + Create the ByocTrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :param voice_url: The URL we should call when the BYOC Trunk receives a call. @@ -542,6 +893,83 @@ async def create_async( :returns: The created ByocTrunkInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + return ByocTrunkInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ByocTrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + instance = ByocTrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -563,12 +991,97 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronously create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) return ByocTrunkInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ByocTrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + instance = ByocTrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -619,6 +1132,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -638,6 +1201,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -664,6 +1228,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -672,6 +1237,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ByocTrunkInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -738,6 +1353,76 @@ async def page_async( ) return ByocTrunkPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ByocTrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ByocTrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ByocTrunkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ByocTrunkPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ByocTrunkPage: """ Retrieve a specific page of ByocTrunkInstance records from the API. diff --git a/twilio/rest/voice/v1/connection_policy/__init__.py b/twilio/rest/voice/v1/connection_policy/__init__.py index e2a56929c7..2d8d1ac47e 100644 --- a/twilio/rest/voice/v1/connection_policy/__init__.py +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyContext] = None @property @@ -91,6 +93,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectionPolicyInstance": """ Fetch the ConnectionPolicyInstance @@ -109,6 +129,24 @@ async def fetch_async(self) -> "ConnectionPolicyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "ConnectionPolicyInstance": @@ -137,6 +175,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ConnectionPolicyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def targets(self) -> ConnectionPolicyTargetList: """ @@ -173,6 +239,20 @@ def __init__(self, version: Version, sid: str): self._targets: Optional[ConnectionPolicyTargetList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectionPolicyInstance @@ -180,10 +260,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -192,64 +294,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ConnectionPolicyInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ConnectionPolicyInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ConnectionPolicyInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyInstance: + """ + Fetch the ConnectionPolicyInstance + + :returns: The fetched ConnectionPolicyInstance + """ + payload, _, _ = self._fetch() return ConnectionPolicyInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> ConnectionPolicyInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConnectionPolicyInstance + Fetch the ConnectionPolicyInstance and return response metadata - :returns: The fetched ConnectionPolicyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + payload, _, _ = await self._fetch_async() return ConnectionPolicyInstance( self._version, payload, sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> ConnectionPolicyInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the ConnectionPolicyInstance + Asynchronous coroutine to fetch the ConnectionPolicyInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :returns: The updated ConnectionPolicyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -263,23 +416,49 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return ConnectionPolicyInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> ConnectionPolicyInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConnectionPolicyInstance + Update the ConnectionPolicyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :returns: The updated ConnectionPolicyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -293,14 +472,43 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return ConnectionPolicyInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def targets(self) -> ConnectionPolicyTargetList: """ @@ -331,6 +539,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: :param payload: Payload response from the API """ + return ConnectionPolicyInstance(self._version, payload) def __repr__(self) -> str: @@ -355,15 +564,12 @@ def __init__(self, version: Version): self._uri = "/ConnectionPolicies" - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> ConnectionPolicyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the ConnectionPolicyInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - - :returns: The created ConnectionPolicyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -377,22 +583,46 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return ConnectionPolicyInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset ) -> ConnectionPolicyInstance: """ - Asynchronously create the ConnectionPolicyInstance + Create the ConnectionPolicyInstance :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :returns: The created ConnectionPolicyInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return ConnectionPolicyInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the ConnectionPolicyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -405,12 +635,39 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronously create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ConnectionPolicyInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -461,6 +718,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -480,6 +787,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -506,6 +814,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -514,6 +823,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConnectionPolicyInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -580,6 +939,76 @@ async def page_async( ) return ConnectionPolicyPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectionPolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectionPolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ConnectionPolicyPage: """ Retrieve a specific page of ConnectionPolicyInstance records from the API. diff --git a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py index 03f4fd607d..2f84ce2e4d 100644 --- a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "connection_policy_sid": connection_policy_sid, "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyTargetContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectionPolicyTargetInstance": """ Fetch the ConnectionPolicyTargetInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "ConnectionPolicyTargetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,60 @@ async def update_async( enabled=enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConnectionPolicyTargetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -205,6 +297,20 @@ def __init__(self, version: Version, connection_policy_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectionPolicyTargetInstance @@ -212,10 +318,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -224,27 +352,43 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> ConnectionPolicyTargetInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the ConnectionPolicyTargetInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched ConnectionPolicyTargetInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyTargetInstance: + """ + Fetch the ConnectionPolicyTargetInstance + + :returns: The fetched ConnectionPolicyTargetInstance + """ + payload, _, _ = self._fetch() return ConnectionPolicyTargetInstance( self._version, payload, @@ -252,22 +396,46 @@ def fetch(self) -> ConnectionPolicyTargetInstance: sid=self._solution["sid"], ) - async def fetch_async(self) -> ConnectionPolicyTargetInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + Fetch the ConnectionPolicyTargetInstance and return response metadata - :returns: The fetched ConnectionPolicyTargetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._fetch_async() return ConnectionPolicyTargetInstance( self._version, payload, @@ -275,24 +443,35 @@ async def fetch_async(self) -> ConnectionPolicyTargetInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, friendly_name: Union[str, object] = values.unset, target: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, weight: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, - ) -> ConnectionPolicyTargetInstance: + ) -> tuple: """ - Update the ConnectionPolicyTargetInstance + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. - :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. - :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. - :param enabled: Whether the Target is enabled. - - :returns: The updated ConnectionPolicyTargetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,10 +489,36 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) return ConnectionPolicyTargetInstance( self._version, payload, @@ -321,16 +526,16 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, target: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, weight: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, - ) -> ConnectionPolicyTargetInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConnectionPolicyTargetInstance + Update the ConnectionPolicyTargetInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. @@ -338,7 +543,36 @@ async def update_async( :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. :param enabled: Whether the Target is enabled. - :returns: The updated ConnectionPolicyTargetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -356,10 +590,36 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) return ConnectionPolicyTargetInstance( self._version, payload, @@ -367,6 +627,40 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -385,6 +679,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstanc :param payload: Payload response from the API """ + return ConnectionPolicyTargetInstance( self._version, payload, @@ -420,24 +715,19 @@ def __init__(self, version: Version, connection_policy_sid: str): **self._solution ) - def create( + def _create( self, target: str, friendly_name: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, weight: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, - ) -> ConnectionPolicyTargetInstance: + ) -> tuple: """ - Create the ConnectionPolicyTargetInstance - - :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. - :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. - :param enabled: Whether the Target is enabled. The default is `true`. + Internal helper for create operation - :returns: The created ConnectionPolicyTargetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -455,26 +745,52 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + payload, _, _ = self._create( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) return ConnectionPolicyTargetInstance( self._version, payload, connection_policy_sid=self._solution["connection_policy_sid"], ) - async def create_async( + def create_with_http_info( self, target: str, friendly_name: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, weight: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, - ) -> ConnectionPolicyTargetInstance: + ) -> ApiResponse: """ - Asynchronously create the ConnectionPolicyTargetInstance + Create the ConnectionPolicyTargetInstance and return response metadata :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. @@ -482,7 +798,35 @@ async def create_async( :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. :param enabled: Whether the Target is enabled. The default is `true`. - :returns: The created ConnectionPolicyTargetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -500,16 +844,75 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronously create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + payload, _, _ = await self._create_async( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) return ConnectionPolicyTargetInstance( self._version, payload, connection_policy_sid=self._solution["connection_policy_sid"], ) + async def create_with_http_info_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyTargetInstance and return response metadata + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -560,6 +963,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -579,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -605,6 +1059,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -613,6 +1068,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConnectionPolicyTargetInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -644,7 +1149,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -677,7 +1184,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyTargetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConnectionPolicyTargetPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: """ @@ -689,7 +1272,9 @@ def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: :returns: Page of ConnectionPolicyTargetInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: """ @@ -701,7 +1286,9 @@ async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: :returns: Page of ConnectionPolicyTargetInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> ConnectionPolicyTargetContext: """ diff --git a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py index 4059be8dd7..fc4a80d633 100644 --- a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py +++ b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,13 +58,12 @@ def __init__(self, version: Version): self._uri = "/DialingPermissions/BulkCountryUpdates" - def create(self, update_request: str) -> BulkCountryUpdateInstance: + def _create(self, update_request: str) -> tuple: """ - Create the BulkCountryUpdateInstance + Internal helper for create operation - :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` - - :returns: The created BulkCountryUpdateInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -77,19 +77,39 @@ def create(self, update_request: str) -> BulkCountryUpdateInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + payload, _, _ = self._create(update_request=update_request) return BulkCountryUpdateInstance(self._version, payload) - async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: + def create_with_http_info(self, update_request: str) -> ApiResponse: """ - Asynchronously create the BulkCountryUpdateInstance + Create the BulkCountryUpdateInstance and return response metadata :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` - :returns: The created BulkCountryUpdateInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(update_request=update_request) + instance = BulkCountryUpdateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, update_request: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -103,12 +123,35 @@ async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Asynchronously create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + payload, _, _ = await self._create_async(update_request=update_request) return BulkCountryUpdateInstance(self._version, payload) + async def create_with_http_info_async(self, update_request: str) -> ApiResponse: + """ + Asynchronously create the BulkCountryUpdateInstance and return response metadata + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + update_request=update_request + ) + instance = BulkCountryUpdateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py index 6a60c23a2f..ed666a1eb8 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "iso_code": iso_code or self.iso_code, } + self._context: Optional[CountryContext] = None @property @@ -96,6 +98,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: """ @@ -132,48 +152,96 @@ def __init__(self, version: Version, iso_code: str): self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None - def fetch(self) -> CountryInstance: + def _fetch(self) -> tuple: """ - Fetch the CountryInstance + Internal helper for fetch operation - - :returns: The fetched CountryInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + :returns: The fetched CountryInstance + """ + payload, _, _ = self._fetch() return CountryInstance( self._version, payload, iso_code=self._solution["iso_code"], ) - async def fetch_async(self) -> CountryInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CountryInstance + Fetch the CountryInstance and return response metadata - :returns: The fetched CountryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + payload, _, _ = await self._fetch_async() return CountryInstance( self._version, payload, iso_code=self._solution["iso_code"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: """ @@ -204,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -318,6 +387,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CountryInstance and returns headers from first page + + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CountryInstance and returns headers from first page + + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, iso_code: Union[str, object] = values.unset, @@ -349,6 +506,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_code=iso_code, @@ -393,6 +551,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -407,6 +566,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CountryInstance and returns headers from first page + + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CountryInstance and returns headers from first page + + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, iso_code: Union[str, object] = values.unset, @@ -521,6 +766,124 @@ async def page_async( ) return CountryPage(self._version, response) + def page_with_http_info( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CountryPage, status code, and headers + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CountryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CountryPage: """ Retrieve a specific page of CountryInstance records from the API. diff --git a/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py index 75300e928c..9e63e78d24 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HighriskSpecialPrefixInstance :param payload: Payload response from the API """ + return HighriskSpecialPrefixInstance( self._version, payload, iso_code=self._solution["iso_code"] ) @@ -138,6 +140,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -157,6 +209,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -183,6 +236,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -191,6 +245,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -222,7 +326,9 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -255,7 +361,83 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HighriskSpecialPrefixPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HighriskSpecialPrefixPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: """ @@ -267,7 +449,9 @@ def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: :returns: Page of HighriskSpecialPrefixInstance """ response = self._version.domain.twilio.request("GET", target_url) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: """ @@ -279,7 +463,9 @@ async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: :returns: Page of HighriskSpecialPrefixInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/voice/v1/dialing_permissions/settings.py b/twilio/rest/voice/v1/dialing_permissions/settings.py index 9e7aa0babb..e1787b3ce5 100644 --- a/twilio/rest/voice/v1/dialing_permissions/settings.py +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,24 @@ async def fetch_async(self) -> "SettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, dialing_permissions_inheritance: Union[bool, object] = values.unset ) -> "SettingsInstance": @@ -96,6 +115,34 @@ async def update_async( dialing_permissions_inheritance=dialing_permissions_inheritance, ) + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the SettingsInstance with HTTP info + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingsInstance with HTTP info + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -118,55 +165,100 @@ def __init__(self, version: Version): self._uri = "/Settings" - def fetch(self) -> SettingsInstance: + def _fetch(self) -> tuple: """ - Fetch the SettingsInstance + Internal helper for fetch operation - - :returns: The fetched SettingsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SettingsInstance: + """ + Fetch the SettingsInstance + + :returns: The fetched SettingsInstance + """ + payload, _, _ = self._fetch() return SettingsInstance( self._version, payload, ) - async def fetch_async(self) -> SettingsInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SettingsInstance + Fetch the SettingsInstance and return response metadata - :returns: The fetched SettingsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SettingsInstance: + """ + Asynchronous coroutine to fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + payload, _, _ = await self._fetch_async() return SettingsInstance( self._version, payload, ) - def update( - self, dialing_permissions_inheritance: Union[bool, object] = values.unset - ) -> SettingsInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SettingsInstance + Asynchronous coroutine to fetch the SettingsInstance and return response metadata - :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. - :returns: The updated SettingsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SettingsInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -182,22 +274,50 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SettingsInstance(self._version, payload) - - async def update_async( + def update( self, dialing_permissions_inheritance: Union[bool, object] = values.unset ) -> SettingsInstance: """ - Asynchronous coroutine to update the SettingsInstance + Update the SettingsInstance :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. :returns: The updated SettingsInstance """ + payload, _, _ = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + return SettingsInstance(self._version, payload) + + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the SettingsInstance and return response metadata + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -212,12 +332,41 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + payload, _, _ = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) return SettingsInstance(self._version, payload) + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingsInstance and return response metadata + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/voice/v1/ip_record.py b/twilio/rest/voice/v1/ip_record.py index 05e9741fa5..9a17301f6d 100644 --- a/twilio/rest/voice/v1/ip_record.py +++ b/twilio/rest/voice/v1/ip_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[IpRecordContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpRecordInstance": """ Fetch the IpRecordInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "IpRecordInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "IpRecordInstance": @@ -138,6 +176,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the IpRecordInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpRecordInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,6 +231,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/IpRecords/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpRecordInstance @@ -172,10 +252,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpRecordInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -184,64 +286,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> IpRecordInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the IpRecordInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched IpRecordInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> IpRecordInstance: + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + payload, _, _ = self._fetch() return IpRecordInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> IpRecordInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the IpRecordInstance + Fetch the IpRecordInstance and return response metadata - :returns: The fetched IpRecordInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> IpRecordInstance: + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + payload, _, _ = await self._fetch_async() return IpRecordInstance( self._version, payload, sid=self._solution["sid"], ) - def update( - self, friendly_name: Union[str, object] = values.unset - ) -> IpRecordInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the IpRecordInstance + Asynchronous coroutine to fetch the IpRecordInstance and return response metadata - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :returns: The updated IpRecordInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -255,22 +408,46 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset ) -> IpRecordInstance: """ - Asynchronous coroutine to update the IpRecordInstance + Update the IpRecordInstance :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :returns: The updated IpRecordInstance """ + payload, _, _ = self._update(friendly_name=friendly_name) + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the IpRecordInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(friendly_name=friendly_name) + instance = IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -283,12 +460,39 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + payload, _, _ = await self._update_async(friendly_name=friendly_name) return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpRecordInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name + ) + instance = IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -307,6 +511,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: :param payload: Payload response from the API """ + return IpRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -331,20 +536,17 @@ def __init__(self, version: Version): self._uri = "/IpRecords" - def create( + def _create( self, ip_address: str, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpRecordInstance: + ) -> tuple: """ - Create the IpRecordInstance + Internal helper for create operation - :param ip_address: An IP address in dotted decimal notation, IPv4 only. - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. - - :returns: The created IpRecordInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -360,20 +562,18 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return IpRecordInstance(self._version, payload) - - async def create_async( + def create( self, ip_address: str, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, ) -> IpRecordInstance: """ - Asynchronously create the IpRecordInstance + Create the IpRecordInstance :param ip_address: An IP address in dotted decimal notation, IPv4 only. :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. @@ -381,6 +581,48 @@ async def create_async( :returns: The created IpRecordInstance """ + payload, _, _ = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + return IpRecordInstance(self._version, payload) + + def create_with_http_info( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the IpRecordInstance and return response metadata + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -395,12 +637,55 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Asynchronously create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + payload, _, _ = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) return IpRecordInstance(self._version, payload) + async def create_with_http_info_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpRecordInstance and return response metadata + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,6 +736,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -470,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,6 +832,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -504,6 +841,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists IpRecordInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -570,6 +957,76 @@ async def page_async( ) return IpRecordPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpRecordPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpRecordPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> IpRecordPage: """ Retrieve a specific page of IpRecordInstance records from the API. diff --git a/twilio/rest/voice/v1/source_ip_mapping.py b/twilio/rest/voice/v1/source_ip_mapping.py index 749d2b0034..d4c30d09f5 100644 --- a/twilio/rest/voice/v1/source_ip_mapping.py +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SourceIpMappingContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SourceIpMappingInstance": """ Fetch the SourceIpMappingInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "SourceIpMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, sip_domain_sid: str) -> "SourceIpMappingInstance": """ Update the SourceIpMappingInstance @@ -128,6 +166,30 @@ async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": sip_domain_sid=sip_domain_sid, ) + def update_with_http_info(self, sip_domain_sid: str) -> ApiResponse: + """ + Update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + sip_domain_sid=sip_domain_sid, + ) + + async def update_with_http_info_async(self, sip_domain_sid: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + sip_domain_sid=sip_domain_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,6 +217,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SourceIpMappings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SourceIpMappingInstance @@ -162,10 +238,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SourceIpMappingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -174,62 +272,115 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SourceIpMappingInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SourceIpMappingInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SourceIpMappingInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self) -> SourceIpMappingInstance: + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + payload, _, _ = self._fetch() return SourceIpMappingInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SourceIpMappingInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SourceIpMappingInstance + Fetch the SourceIpMappingInstance and return response metadata - :returns: The fetched SourceIpMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + payload, _, _ = await self._fetch_async() return SourceIpMappingInstance( self._version, payload, sid=self._solution["sid"], ) - def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SourceIpMappingInstance + Asynchronous coroutine to fetch the SourceIpMappingInstance and return response metadata - :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - :returns: The updated SourceIpMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, sip_domain_sid: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -243,21 +394,43 @@ def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + payload, _, _ = self._update(sip_domain_sid=sip_domain_sid) return SourceIpMappingInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: + def update_with_http_info(self, sip_domain_sid: str) -> ApiResponse: """ - Asynchronous coroutine to update the SourceIpMappingInstance + Update the SourceIpMappingInstance and return response metadata :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - :returns: The updated SourceIpMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(sip_domain_sid=sip_domain_sid) + instance = SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, sip_domain_sid: str) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -271,14 +444,39 @@ async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + payload, _, _ = await self._update_async(sip_domain_sid=sip_domain_sid) return SourceIpMappingInstance( self._version, payload, sid=self._solution["sid"] ) + async def update_with_http_info_async(self, sip_domain_sid: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SourceIpMappingInstance and return response metadata + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -297,6 +495,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: :param payload: Payload response from the API """ + return SourceIpMappingInstance(self._version, payload) def __repr__(self) -> str: @@ -321,16 +520,12 @@ def __init__(self, version: Version): self._uri = "/SourceIpMappings" - def create( - self, ip_record_sid: str, sip_domain_sid: str - ) -> SourceIpMappingInstance: + def _create(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: """ - Create the SourceIpMappingInstance + Internal helper for create operation - :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. - :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - - :returns: The created SourceIpMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -345,23 +540,50 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SourceIpMappingInstance(self._version, payload) - - async def create_async( + def create( self, ip_record_sid: str, sip_domain_sid: str ) -> SourceIpMappingInstance: """ - Asynchronously create the SourceIpMappingInstance + Create the SourceIpMappingInstance :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. :returns: The created SourceIpMappingInstance """ + payload, _, _ = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + return SourceIpMappingInstance(self._version, payload) + + def create_with_http_info( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Create the SourceIpMappingInstance and return response metadata + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -375,12 +597,43 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Asynchronously create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + payload, _, _ = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) return SourceIpMappingInstance(self._version, payload) + async def create_with_http_info_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Asynchronously create the SourceIpMappingInstance and return response metadata + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -431,6 +684,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -450,6 +753,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -476,6 +780,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -484,6 +789,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SourceIpMappingInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -550,6 +905,76 @@ async def page_async( ) return SourceIpMappingPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SourceIpMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SourceIpMappingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SourceIpMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SourceIpMappingPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SourceIpMappingPage: """ Retrieve a specific page of SourceIpMappingInstance records from the API. diff --git a/twilio/rest/voice/v2/__init__.py b/twilio/rest/voice/v2/__init__.py new file mode 100644 index 0000000000..6256684366 --- /dev/null +++ b/twilio/rest/voice/v2/__init__.py @@ -0,0 +1,79 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.voice.v2.account_default_configuration import ( + AccountDefaultConfigurationList, +) +from twilio.rest.voice.v2.configuration import ConfigurationList +from twilio.rest.voice.v2.recording import RecordingList +from twilio.rest.voice.v2.transcription import TranscriptionList +from twilio.rest.voice.v2.type import TypeList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Voice + + :param domain: The Twilio.voice domain + """ + super().__init__(domain, "v2") + self._account_default_configuration: Optional[ + AccountDefaultConfigurationList + ] = None + self._configurations: Optional[ConfigurationList] = None + self._recording: Optional[RecordingList] = None + self._transcription: Optional[TranscriptionList] = None + self._type: Optional[TypeList] = None + + @property + def account_default_configuration(self) -> AccountDefaultConfigurationList: + if self._account_default_configuration is None: + self._account_default_configuration = AccountDefaultConfigurationList(self) + return self._account_default_configuration + + @property + def configurations(self) -> ConfigurationList: + if self._configurations is None: + self._configurations = ConfigurationList(self) + return self._configurations + + @property + def recording(self) -> RecordingList: + if self._recording is None: + self._recording = RecordingList(self) + return self._recording + + @property + def transcription(self) -> TranscriptionList: + if self._transcription is None: + self._transcription = TranscriptionList(self) + return self._transcription + + @property + def type(self) -> TypeList: + if self._type is None: + self._type = TypeList(self) + return self._type + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2>" diff --git a/twilio/rest/voice/v2/account_default_configuration.py b/twilio/rest/voice/v2/account_default_configuration.py new file mode 100644 index 0000000000..4657f3c11c --- /dev/null +++ b/twilio/rest/voice/v2/account_default_configuration.py @@ -0,0 +1,838 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AccountDefaultConfigurationInstance(InstanceResource): + + class VoiceV2AccountDefaultConfigurationRequest(object): + """ + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "description": self.description, + "configuration": self.configuration, + } + + """ + :ivar account_sid: Account sid + :ivar description: The description + :ivar date_created: + :ivar date_updated: + :ivar configuration: + :ivar message: Error message + :ivar code: Twilio error code + :ivar status: status code + :ivar more_info: More information about the error + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], type: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = payload.get("code") + self.status: Optional[int] = payload.get("status") + self.more_info: Optional[str] = payload.get("more_info") + + self._solution = { + "type": type or self.type, + } + + self._context: Optional[AccountDefaultConfigurationContext] = None + + @property + def _proxy(self) -> "AccountDefaultConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountDefaultConfigurationContext for this AccountDefaultConfigurationInstance + """ + if self._context is None: + self._context = AccountDefaultConfigurationContext( + self._version, + type=self._solution["type"], + ) + return self._context + + def create( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> "AccountDefaultConfigurationInstance": + """ + Create the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The created AccountDefaultConfigurationInstance + """ + return self._proxy.create( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + async def create_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> "AccountDefaultConfigurationInstance": + """ + Asynchronous coroutine to create the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The created AccountDefaultConfigurationInstance + """ + return await self._proxy.create_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + def create_with_http_info( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the AccountDefaultConfigurationInstance with HTTP info + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + async def create_with_http_info_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the AccountDefaultConfigurationInstance with HTTP info + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + def delete(self) -> bool: + """ + Deletes the AccountDefaultConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountDefaultConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AccountDefaultConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AccountDefaultConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "AccountDefaultConfigurationInstance": + """ + Fetch the AccountDefaultConfigurationInstance + + + :returns: The fetched AccountDefaultConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountDefaultConfigurationInstance": + """ + Asynchronous coroutine to fetch the AccountDefaultConfigurationInstance + + + :returns: The fetched AccountDefaultConfigurationInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountDefaultConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountDefaultConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> "AccountDefaultConfigurationInstance": + """ + Update the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The updated AccountDefaultConfigurationInstance + """ + return self._proxy.update( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + async def update_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> "AccountDefaultConfigurationInstance": + """ + Asynchronous coroutine to update the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The updated AccountDefaultConfigurationInstance + """ + return await self._proxy.update_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + def update_with_http_info( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AccountDefaultConfigurationInstance with HTTP info + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + async def update_with_http_info_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountDefaultConfigurationInstance with HTTP info + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.AccountDefaultConfigurationInstance {}>".format( + context + ) + + +class AccountDefaultConfigurationContext(InstanceContext): + + class VoiceV2AccountDefaultConfigurationRequest(object): + """ + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version, type: str): + """ + Initialize the AccountDefaultConfigurationContext + + :param version: Version that contains the resource + :param type: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + } + self._uri = "/AccountDefaultConfiguration/{type}".format(**self._solution) + + def _create( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_account_default_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> AccountDefaultConfigurationInstance: + """ + Create the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The created AccountDefaultConfigurationInstance + """ + payload, _, _ = self._create( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + return AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + def create_with_http_info( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the AccountDefaultConfigurationInstance and return response metadata + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + instance = AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_account_default_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> AccountDefaultConfigurationInstance: + """ + Asynchronous coroutine to create the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The created AccountDefaultConfigurationInstance + """ + payload, _, _ = await self._create_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + return AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + async def create_with_http_info_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the AccountDefaultConfigurationInstance and return response metadata + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + instance = AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the AccountDefaultConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AccountDefaultConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AccountDefaultConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AccountDefaultConfigurationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> AccountDefaultConfigurationInstance: + """ + Fetch the AccountDefaultConfigurationInstance + + + :returns: The fetched AccountDefaultConfigurationInstance + """ + payload, _, _ = self._fetch() + return AccountDefaultConfigurationInstance( + self._version, + payload, + type=self._solution["type"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountDefaultConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AccountDefaultConfigurationInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> AccountDefaultConfigurationInstance: + """ + Asynchronous coroutine to fetch the AccountDefaultConfigurationInstance + + + :returns: The fetched AccountDefaultConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return AccountDefaultConfigurationInstance( + self._version, + payload, + type=self._solution["type"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountDefaultConfigurationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AccountDefaultConfigurationInstance( + self._version, + payload, + type=self._solution["type"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_account_default_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> AccountDefaultConfigurationInstance: + """ + Update the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The updated AccountDefaultConfigurationInstance + """ + payload, _, _ = self._update( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + return AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + def update_with_http_info( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AccountDefaultConfigurationInstance and return response metadata + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + instance = AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_account_default_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> AccountDefaultConfigurationInstance: + """ + Asynchronous coroutine to update the AccountDefaultConfigurationInstance + + :param voice_v2_account_default_configuration_request: + + :returns: The updated AccountDefaultConfigurationInstance + """ + payload, _, _ = await self._update_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + return AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + async def update_with_http_info_async( + self, + voice_v2_account_default_configuration_request: Union[ + VoiceV2AccountDefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountDefaultConfigurationInstance and return response metadata + + :param voice_v2_account_default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_v2_account_default_configuration_request=voice_v2_account_default_configuration_request + ) + instance = AccountDefaultConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.AccountDefaultConfigurationContext {}>".format(context) + + +class AccountDefaultConfigurationList(ListResource): + + class VoiceV2AccountDefaultConfigurationRequest(object): + """ + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version): + """ + Initialize the AccountDefaultConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, type: str) -> AccountDefaultConfigurationContext: + """ + Constructs a AccountDefaultConfigurationContext + + :param type: + """ + return AccountDefaultConfigurationContext(self._version, type=type) + + def __call__(self, type: str) -> AccountDefaultConfigurationContext: + """ + Constructs a AccountDefaultConfigurationContext + + :param type: + """ + return AccountDefaultConfigurationContext(self._version, type=type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.AccountDefaultConfigurationList>" diff --git a/twilio/rest/voice/v2/configuration/__init__.py b/twilio/rest/voice/v2/configuration/__init__.py new file mode 100644 index 0000000000..513cab3a3a --- /dev/null +++ b/twilio/rest/voice/v2/configuration/__init__.py @@ -0,0 +1,432 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.voice.v2.configuration.default import DefaultList + + +class ConfigurationInstance(InstanceResource): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + """ + :ivar id: Configuration Identifier + :ivar account_sid: Account sid + :ivar unique_name: The unique name + :ivar description: The description + :ivar date_created: + :ivar date_updated: + :ivar configuration: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], type: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + + self._solution = { + "type": type or self.type, + } + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + type=self._solution["type"], + ) + return self._context + + def create( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Create the ConfigurationInstance + + :param voice_v2_configuration_request: + + :returns: The created ConfigurationInstance + """ + return self._proxy.create( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + async def create_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to create the ConfigurationInstance + + :param voice_v2_configuration_request: + + :returns: The created ConfigurationInstance + """ + return await self._proxy.create_async( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + def create_with_http_info( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConfigurationInstance with HTTP info + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + async def create_with_http_info_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ConfigurationInstance with HTTP info + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + @property + def default(self) -> DefaultList: + """ + Access the default + """ + return self._proxy.default + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.ConfigurationInstance {}>".format(context) + + +class ConfigurationContext(InstanceContext): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version, type: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param type: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + } + self._uri = "/Configurations/{type}".format(**self._solution) + + self._default: Optional[DefaultList] = None + + def _create( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Create the ConfigurationInstance + + :param voice_v2_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = self._create( + voice_v2_configuration_request=voice_v2_configuration_request + ) + return ConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + def create_with_http_info( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the ConfigurationInstance and return response metadata + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + voice_v2_configuration_request=voice_v2_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to create the ConfigurationInstance + + :param voice_v2_configuration_request: + + :returns: The created ConfigurationInstance + """ + payload, _, _ = await self._create_async( + voice_v2_configuration_request=voice_v2_configuration_request + ) + return ConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + + async def create_with_http_info_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the ConfigurationInstance and return response metadata + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + voice_v2_configuration_request=voice_v2_configuration_request + ) + instance = ConfigurationInstance( + self._version, payload, type=self._solution["type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def default(self) -> DefaultList: + """ + Access the default + """ + if self._default is None: + self._default = DefaultList( + self._version, + self._solution["type"], + ) + return self._default + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.ConfigurationContext {}>".format(context) + + +class ConfigurationList(ListResource): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, type: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param type: + """ + return ConfigurationContext(self._version, type=type) + + def __call__(self, type: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param type: + """ + return ConfigurationContext(self._version, type=type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.ConfigurationList>" diff --git a/twilio/rest/voice/v2/configuration/default.py b/twilio/rest/voice/v2/configuration/default.py new file mode 100644 index 0000000000..9a37632e19 --- /dev/null +++ b/twilio/rest/voice/v2/configuration/default.py @@ -0,0 +1,320 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DefaultInstance(InstanceResource): + + class DefaultConfigurationRequest(object): + """ + :ivar configuration_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_id: Optional[str] = payload.get("configuration_id") + + def to_dict(self): + return { + "configuration_id": self.configuration_id, + } + + """ + :ivar message: Error message + :ivar code: Twilio error code + :ivar status: status code + :ivar more_info: More information about the error + :ivar id: Configuration Identifier + :ivar account_sid: Account sid + :ivar unique_name: The unique name + :ivar description: The description + :ivar date_created: + :ivar date_updated: + :ivar configuration: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], type: str): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = payload.get("code") + self.status: Optional[int] = payload.get("status") + self.more_info: Optional[str] = payload.get("more_info") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + + self._solution = { + "type": type, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.DefaultInstance {}>".format(context) + + +class DefaultList(ListResource): + + class DefaultConfigurationRequest(object): + """ + :ivar configuration_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_id: Optional[str] = payload.get("configuration_id") + + def to_dict(self): + return { + "configuration_id": self.configuration_id, + } + + def __init__(self, version: Version, type: str): + """ + Initialize the DefaultList + + :param version: Version that contains the resource + :param type: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + } + self._uri = "/Configurations/{type}/Default".format(**self._solution) + + def _create( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = default_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> DefaultInstance: + """ + Create the DefaultInstance + + :param default_configuration_request: + + :returns: The created DefaultInstance + """ + payload, _, _ = self._create( + default_configuration_request=default_configuration_request + ) + return DefaultInstance(self._version, payload, type=self._solution["type"]) + + def create_with_http_info( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the DefaultInstance and return response metadata + + :param default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + default_configuration_request=default_configuration_request + ) + instance = DefaultInstance(self._version, payload, type=self._solution["type"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = default_configuration_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> DefaultInstance: + """ + Asynchronously create the DefaultInstance + + :param default_configuration_request: + + :returns: The created DefaultInstance + """ + payload, _, _ = await self._create_async( + default_configuration_request=default_configuration_request + ) + return DefaultInstance(self._version, payload, type=self._solution["type"]) + + async def create_with_http_info_async( + self, + default_configuration_request: Union[ + DefaultConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the DefaultInstance and return response metadata + + :param default_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + default_configuration_request=default_configuration_request + ) + instance = DefaultInstance(self._version, payload, type=self._solution["type"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> DefaultInstance: + """ + Fetch the DefaultInstance + + + :returns: The fetched DefaultInstance + """ + payload, _, _ = self._fetch() + return DefaultInstance(self._version, payload, type=self._solution["type"]) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DefaultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = DefaultInstance(self._version, payload, type=self._solution["type"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> DefaultInstance: + """ + Asynchronously fetch the DefaultInstance + + + :returns: The fetched DefaultInstance + """ + payload, _, _ = await self._fetch_async() + return DefaultInstance(self._version, payload, type=self._solution["type"]) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously fetch the DefaultInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DefaultInstance(self._version, payload, type=self._solution["type"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.DefaultList>" diff --git a/twilio/rest/voice/v2/recording.py b/twilio/rest/voice/v2/recording.py new file mode 100644 index 0000000000..0ae6ac1ac4 --- /dev/null +++ b/twilio/rest/voice/v2/recording.py @@ -0,0 +1,1136 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingInstance(InstanceResource): + + class VoiceV2ConfigurationRecordingCompositionPolicy(object): + """ + :ivar channels: The number of channels to be composed. + :ivar trim: Trim the silence in the recordings. + :ivar track: The audio track to record for the call. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channels: Optional["RecordingInstance.str"] = payload.get("channels") + self.trim: Optional["RecordingInstance.str"] = payload.get("trim") + self.track: Optional["RecordingInstance.str"] = payload.get("track") + + def to_dict(self): + return { + "channels": self.channels, + "trim": self.trim, + "track": self.track, + } + + class VoiceV2ConfigurationRecordingConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Recording\" for this resource. + :ivar composition_policy: + :ivar call_recording_status_callback: + :ivar conference_recording_status_callback: + :ivar features: The features to apply to this recording. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["RecordingInstance.str"] = payload.get( + "configurationType" + ) + self.composition_policy: Optional[ + RecordingList.VoiceV2ConfigurationRecordingCompositionPolicy + ] = payload.get("compositionPolicy") + self.call_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("callRecordingStatusCallback") + self.conference_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("conferenceRecordingStatusCallback") + self.features: Optional[ + List[RecordingList.VoiceV2ConfigurationRecordingFeature] + ] = payload.get("features") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "compositionPolicy": ( + self.composition_policy.to_dict() + if self.composition_policy is not None + else None + ), + "callRecordingStatusCallback": ( + self.call_recording_status_callback.to_dict() + if self.call_recording_status_callback is not None + else None + ), + "conferenceRecordingStatusCallback": ( + self.conference_recording_status_callback.to_dict() + if self.conference_recording_status_callback is not None + else None + ), + "features": ( + [features.to_dict() for features in self.features] + if self.features is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingFeature(object): + """ + :ivar type: The type of feature. + :ivar feature_id: The ID of the feature. + :ivar description: The description of the feature. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["RecordingInstance.str"] = payload.get("type") + self.feature_id: Optional[str] = payload.get("featureId") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "type": self.type, + "featureId": self.feature_id, + "description": self.description, + } + + class VoiceV2ConfigurationRecordingRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + RecordingList.VoiceV2ConfigurationRecordingConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingStatusCallback(object): + """ + :ivar url: The recording status callback URL. + :ivar method: The recording status callback method. + :ivar events: The recording status callback events. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["RecordingInstance.str"] = payload.get("method") + self.events: Optional[List[Enumstr]] = payload.get("events") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + "events": self.events, + } + + """ + :ivar id: Configuration Identifier. + :ivar account_sid: Account sid. + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar date_created: + :ivar date_updated: + :ivar configuration: + :ivar message: Error message + :ivar code: Twilio error code + :ivar status: status code + :ivar more_info: More information about the error + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + id_or_unique_name: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[str] = payload.get("configuration") + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = payload.get("code") + self.status: Optional[int] = payload.get("status") + self.more_info: Optional[str] = payload.get("more_info") + + self._solution = { + "id_or_unique_name": id_or_unique_name or self.id_or_unique_name, + } + + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request, + ) + + async def update_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request, + ) + + def update_with_http_info( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request, + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + class VoiceV2ConfigurationRecordingCompositionPolicy(object): + """ + :ivar channels: The number of channels to be composed. + :ivar trim: Trim the silence in the recordings. + :ivar track: The audio track to record for the call. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channels: Optional["RecordingInstance.str"] = payload.get("channels") + self.trim: Optional["RecordingInstance.str"] = payload.get("trim") + self.track: Optional["RecordingInstance.str"] = payload.get("track") + + def to_dict(self): + return { + "channels": self.channels, + "trim": self.trim, + "track": self.track, + } + + class VoiceV2ConfigurationRecordingConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Recording\" for this resource. + :ivar composition_policy: + :ivar call_recording_status_callback: + :ivar conference_recording_status_callback: + :ivar features: The features to apply to this recording. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["RecordingInstance.str"] = payload.get( + "configurationType" + ) + self.composition_policy: Optional[ + RecordingList.VoiceV2ConfigurationRecordingCompositionPolicy + ] = payload.get("compositionPolicy") + self.call_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("callRecordingStatusCallback") + self.conference_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("conferenceRecordingStatusCallback") + self.features: Optional[ + List[RecordingList.VoiceV2ConfigurationRecordingFeature] + ] = payload.get("features") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "compositionPolicy": ( + self.composition_policy.to_dict() + if self.composition_policy is not None + else None + ), + "callRecordingStatusCallback": ( + self.call_recording_status_callback.to_dict() + if self.call_recording_status_callback is not None + else None + ), + "conferenceRecordingStatusCallback": ( + self.conference_recording_status_callback.to_dict() + if self.conference_recording_status_callback is not None + else None + ), + "features": ( + [features.to_dict() for features in self.features] + if self.features is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingFeature(object): + """ + :ivar type: The type of feature. + :ivar feature_id: The ID of the feature. + :ivar description: The description of the feature. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["RecordingInstance.str"] = payload.get("type") + self.feature_id: Optional[str] = payload.get("featureId") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "type": self.type, + "featureId": self.feature_id, + "description": self.description, + } + + class VoiceV2ConfigurationRecordingRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + RecordingList.VoiceV2ConfigurationRecordingConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingStatusCallback(object): + """ + :ivar url: The recording status callback URL. + :ivar method: The recording status callback method. + :ivar events: The recording status callback events. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["RecordingInstance.str"] = payload.get("method") + self.events: Optional[List[Enumstr]] = payload.get("events") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + "events": self.events, + } + + def __init__(self, version: Version, id_or_unique_name: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param id_or_unique_name: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id_or_unique_name": id_or_unique_name, + } + self._uri = "/Configurations/Recording/{id_or_unique_name}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_recording_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The updated RecordingInstance + """ + payload, _, _ = self._update( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + return RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def update_with_http_info( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance and return response metadata + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + instance = RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_recording_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The updated RecordingInstance + """ + payload, _, _ = await self._update_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + return RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance and return response metadata + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + instance = RecordingInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.RecordingContext {}>".format(context) + + +class RecordingList(ListResource): + + class VoiceV2ConfigurationRecordingCompositionPolicy(object): + """ + :ivar channels: The number of channels to be composed. + :ivar trim: Trim the silence in the recordings. + :ivar track: The audio track to record for the call. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channels: Optional["RecordingInstance.str"] = payload.get("channels") + self.trim: Optional["RecordingInstance.str"] = payload.get("trim") + self.track: Optional["RecordingInstance.str"] = payload.get("track") + + def to_dict(self): + return { + "channels": self.channels, + "trim": self.trim, + "track": self.track, + } + + class VoiceV2ConfigurationRecordingConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Recording\" for this resource. + :ivar composition_policy: + :ivar call_recording_status_callback: + :ivar conference_recording_status_callback: + :ivar features: The features to apply to this recording. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["RecordingInstance.str"] = payload.get( + "configurationType" + ) + self.composition_policy: Optional[ + RecordingList.VoiceV2ConfigurationRecordingCompositionPolicy + ] = payload.get("compositionPolicy") + self.call_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("callRecordingStatusCallback") + self.conference_recording_status_callback: Optional[ + RecordingList.VoiceV2ConfigurationRecordingStatusCallback + ] = payload.get("conferenceRecordingStatusCallback") + self.features: Optional[ + List[RecordingList.VoiceV2ConfigurationRecordingFeature] + ] = payload.get("features") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "compositionPolicy": ( + self.composition_policy.to_dict() + if self.composition_policy is not None + else None + ), + "callRecordingStatusCallback": ( + self.call_recording_status_callback.to_dict() + if self.call_recording_status_callback is not None + else None + ), + "conferenceRecordingStatusCallback": ( + self.conference_recording_status_callback.to_dict() + if self.conference_recording_status_callback is not None + else None + ), + "features": ( + [features.to_dict() for features in self.features] + if self.features is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingFeature(object): + """ + :ivar type: The type of feature. + :ivar feature_id: The ID of the feature. + :ivar description: The description of the feature. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["RecordingInstance.str"] = payload.get("type") + self.feature_id: Optional[str] = payload.get("featureId") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "type": self.type, + "featureId": self.feature_id, + "description": self.description, + } + + class VoiceV2ConfigurationRecordingRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + RecordingList.VoiceV2ConfigurationRecordingConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationRecordingStatusCallback(object): + """ + :ivar url: The recording status callback URL. + :ivar method: The recording status callback method. + :ivar events: The recording status callback events. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["RecordingInstance.str"] = payload.get("method") + self.events: Optional[List[Enumstr]] = payload.get("events") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + "events": self.events, + } + + def __init__(self, version: Version): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configurations/Recording" + + def _create( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_recording_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> RecordingInstance: + """ + Create the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The created RecordingInstance + """ + payload, _, _ = self._create( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + return RecordingInstance(self._version, payload) + + def create_with_http_info( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingInstance and return response metadata + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + instance = RecordingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_recording_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> RecordingInstance: + """ + Asynchronously create the RecordingInstance + + :param voice_v2_configuration_recording_request: + + :returns: The created RecordingInstance + """ + payload, _, _ = await self._create_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + return RecordingInstance(self._version, payload) + + async def create_with_http_info_async( + self, + voice_v2_configuration_recording_request: Union[ + VoiceV2ConfigurationRecordingRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RecordingInstance and return response metadata + + :param voice_v2_configuration_recording_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + voice_v2_configuration_recording_request=voice_v2_configuration_recording_request + ) + instance = RecordingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, id_or_unique_name: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param id_or_unique_name: + """ + return RecordingContext(self._version, id_or_unique_name=id_or_unique_name) + + def __call__(self, id_or_unique_name: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param id_or_unique_name: + """ + return RecordingContext(self._version, id_or_unique_name=id_or_unique_name) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.RecordingList>" diff --git a/twilio/rest/voice/v2/transcription.py b/twilio/rest/voice/v2/transcription.py new file mode 100644 index 0000000000..d76c1f421d --- /dev/null +++ b/twilio/rest/voice/v2/transcription.py @@ -0,0 +1,1067 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TranscriptionInstance(InstanceResource): + + class VoiceV2ConfigurationTranscriptionConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Transcription\" for this resource. + :ivar transcription_engine: The transcription engine provider. Supported values: 'google', 'deepgram', 'twilio_managed'. When using 'twilio_managed', do not specify a speechModel. + :ivar speech_model: The specific speech model to use for transcription. Valid models depend on transcriptionEngine: For 'google': chirp_2. For 'deepgram': nova-3, nova-2. For 'twilio_managed': twilio_managed. + :ivar language: Controls how the ASR handles language. Can be a supported BCP-47 language code, or 'multi' for multilingual code switching (Deepgram engine only). Supported language codes: en-US, en-GB, en-AU, de-DE, fr-FR, it-IT, es-MX, es-ES, es-US, pt-BR, pt-PT, nl-NL, no-NO, pl-PL, sv-SE, da-DK. + :ivar transcription_status_callback: + :ivar conversation_configuration_id: The ID of the Maestro Conversations Configuration for transcription storage and optional add-ons. + :ivar participant_defaults: Default participant roles and channel mappings for diarization and implicit participant creation. Must include exactly 2 participants mapping audioChannelIndex 1 and 2. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["TranscriptionInstance.str"] = ( + payload.get("configurationType") + ) + self.transcription_engine: Optional[str] = payload.get( + "transcriptionEngine" + ) + self.speech_model: Optional[str] = payload.get("speechModel") + self.language: Optional[str] = payload.get("language") + self.transcription_status_callback: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionStatusCallback + ] = payload.get("transcriptionStatusCallback") + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.participant_defaults: Optional[ + List[ + TranscriptionList.VoiceV2ConfigurationTranscriptionParticipantDefault + ] + ] = payload.get("participantDefaults") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "transcriptionEngine": self.transcription_engine, + "speechModel": self.speech_model, + "language": self.language, + "transcriptionStatusCallback": ( + self.transcription_status_callback.to_dict() + if self.transcription_status_callback is not None + else None + ), + "conversationConfigurationId": self.conversation_configuration_id, + "participantDefaults": ( + [ + participant_defaults.to_dict() + for participant_defaults in self.participant_defaults + ] + if self.participant_defaults is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionParticipantDefault(object): + """ + :ivar audio_channel_index: One-based index of the audio channel in a multi-channel recording associated with this role. + :ivar type: The participant role to apply when inferring participants. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + self.type: Optional["TranscriptionInstance.str"] = payload.get("type") + + def to_dict(self): + return { + "audioChannelIndex": self.audio_channel_index, + "type": self.type, + } + + class VoiceV2ConfigurationTranscriptionRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionStatusCallback(object): + """ + :ivar url: The webhook callback URL. + :ivar method: The HTTP method to use for the webhook callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["TranscriptionInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + """ + :ivar id: Configuration Identifier. + :ivar account_sid: Account sid. + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar date_created: + :ivar date_updated: + :ivar configuration: + :ivar message: Error message + :ivar code: Twilio error code + :ivar status: status code + :ivar more_info: More information about the error + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + id_or_unique_name: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[str] = payload.get("configuration") + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = payload.get("code") + self.status: Optional[int] = payload.get("status") + self.more_info: Optional[str] = payload.get("more_info") + + self._solution = { + "id_or_unique_name": id_or_unique_name or self.id_or_unique_name, + } + + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> "TranscriptionInstance": + """ + Update the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The updated TranscriptionInstance + """ + return self._proxy.update( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request, + ) + + async def update_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> "TranscriptionInstance": + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The updated TranscriptionInstance + """ + return await self._proxy.update_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request, + ) + + def update_with_http_info( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionInstance with HTTP info + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request, + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance with HTTP info + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.TranscriptionInstance {}>".format(context) + + +class TranscriptionContext(InstanceContext): + + class VoiceV2ConfigurationTranscriptionConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Transcription\" for this resource. + :ivar transcription_engine: The transcription engine provider. Supported values: 'google', 'deepgram', 'twilio_managed'. When using 'twilio_managed', do not specify a speechModel. + :ivar speech_model: The specific speech model to use for transcription. Valid models depend on transcriptionEngine: For 'google': chirp_2. For 'deepgram': nova-3, nova-2. For 'twilio_managed': twilio_managed. + :ivar language: Controls how the ASR handles language. Can be a supported BCP-47 language code, or 'multi' for multilingual code switching (Deepgram engine only). Supported language codes: en-US, en-GB, en-AU, de-DE, fr-FR, it-IT, es-MX, es-ES, es-US, pt-BR, pt-PT, nl-NL, no-NO, pl-PL, sv-SE, da-DK. + :ivar transcription_status_callback: + :ivar conversation_configuration_id: The ID of the Maestro Conversations Configuration for transcription storage and optional add-ons. + :ivar participant_defaults: Default participant roles and channel mappings for diarization and implicit participant creation. Must include exactly 2 participants mapping audioChannelIndex 1 and 2. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["TranscriptionInstance.str"] = ( + payload.get("configurationType") + ) + self.transcription_engine: Optional[str] = payload.get( + "transcriptionEngine" + ) + self.speech_model: Optional[str] = payload.get("speechModel") + self.language: Optional[str] = payload.get("language") + self.transcription_status_callback: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionStatusCallback + ] = payload.get("transcriptionStatusCallback") + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.participant_defaults: Optional[ + List[ + TranscriptionList.VoiceV2ConfigurationTranscriptionParticipantDefault + ] + ] = payload.get("participantDefaults") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "transcriptionEngine": self.transcription_engine, + "speechModel": self.speech_model, + "language": self.language, + "transcriptionStatusCallback": ( + self.transcription_status_callback.to_dict() + if self.transcription_status_callback is not None + else None + ), + "conversationConfigurationId": self.conversation_configuration_id, + "participantDefaults": ( + [ + participant_defaults.to_dict() + for participant_defaults in self.participant_defaults + ] + if self.participant_defaults is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionParticipantDefault(object): + """ + :ivar audio_channel_index: One-based index of the audio channel in a multi-channel recording associated with this role. + :ivar type: The participant role to apply when inferring participants. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + self.type: Optional["TranscriptionInstance.str"] = payload.get("type") + + def to_dict(self): + return { + "audioChannelIndex": self.audio_channel_index, + "type": self.type, + } + + class VoiceV2ConfigurationTranscriptionRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionStatusCallback(object): + """ + :ivar url: The webhook callback URL. + :ivar method: The HTTP method to use for the webhook callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["TranscriptionInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + def __init__(self, version: Version, id_or_unique_name: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param id_or_unique_name: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id_or_unique_name": id_or_unique_name, + } + self._uri = "/Configurations/Transcription/{id_or_unique_name}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_transcription_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = self._update( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + return TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def update_with_http_info( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TranscriptionInstance and return response metadata + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + instance = TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_transcription_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = await self._update_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + return TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance and return response metadata + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + instance = TranscriptionInstance( + self._version, + payload, + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.TranscriptionContext {}>".format(context) + + +class TranscriptionList(ListResource): + + class VoiceV2ConfigurationTranscriptionConfiguration(object): + """ + :ivar configuration_type: The configuration type discriminator. Always \"Transcription\" for this resource. + :ivar transcription_engine: The transcription engine provider. Supported values: 'google', 'deepgram', 'twilio_managed'. When using 'twilio_managed', do not specify a speechModel. + :ivar speech_model: The specific speech model to use for transcription. Valid models depend on transcriptionEngine: For 'google': chirp_2. For 'deepgram': nova-3, nova-2. For 'twilio_managed': twilio_managed. + :ivar language: Controls how the ASR handles language. Can be a supported BCP-47 language code, or 'multi' for multilingual code switching (Deepgram engine only). Supported language codes: en-US, en-GB, en-AU, de-DE, fr-FR, it-IT, es-MX, es-ES, es-US, pt-BR, pt-PT, nl-NL, no-NO, pl-PL, sv-SE, da-DK. + :ivar transcription_status_callback: + :ivar conversation_configuration_id: The ID of the Maestro Conversations Configuration for transcription storage and optional add-ons. + :ivar participant_defaults: Default participant roles and channel mappings for diarization and implicit participant creation. Must include exactly 2 participants mapping audioChannelIndex 1 and 2. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration_type: Optional["TranscriptionInstance.str"] = ( + payload.get("configurationType") + ) + self.transcription_engine: Optional[str] = payload.get( + "transcriptionEngine" + ) + self.speech_model: Optional[str] = payload.get("speechModel") + self.language: Optional[str] = payload.get("language") + self.transcription_status_callback: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionStatusCallback + ] = payload.get("transcriptionStatusCallback") + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.participant_defaults: Optional[ + List[ + TranscriptionList.VoiceV2ConfigurationTranscriptionParticipantDefault + ] + ] = payload.get("participantDefaults") + + def to_dict(self): + return { + "configurationType": self.configuration_type, + "transcriptionEngine": self.transcription_engine, + "speechModel": self.speech_model, + "language": self.language, + "transcriptionStatusCallback": ( + self.transcription_status_callback.to_dict() + if self.transcription_status_callback is not None + else None + ), + "conversationConfigurationId": self.conversation_configuration_id, + "participantDefaults": ( + [ + participant_defaults.to_dict() + for participant_defaults in self.participant_defaults + ] + if self.participant_defaults is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionParticipantDefault(object): + """ + :ivar audio_channel_index: One-based index of the audio channel in a multi-channel recording associated with this role. + :ivar type: The participant role to apply when inferring participants. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + self.type: Optional["TranscriptionInstance.str"] = payload.get("type") + + def to_dict(self): + return { + "audioChannelIndex": self.audio_channel_index, + "type": self.type, + } + + class VoiceV2ConfigurationTranscriptionRequest(object): + """ + :ivar unique_name: The unique name. + :ivar description: The description. + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[ + TranscriptionList.VoiceV2ConfigurationTranscriptionConfiguration + ] = payload.get("configuration") + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + } + + class VoiceV2ConfigurationTranscriptionStatusCallback(object): + """ + :ivar url: The webhook callback URL. + :ivar method: The HTTP method to use for the webhook callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional["TranscriptionInstance.str"] = payload.get("method") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + } + + def __init__(self, version: Version): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configurations/Transcription" + + def _create( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_transcription_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The created TranscriptionInstance + """ + payload, _, _ = self._create( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + return TranscriptionInstance(self._version, payload) + + def create_with_http_info( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptionInstance and return response metadata + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_transcription_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param voice_v2_configuration_transcription_request: + + :returns: The created TranscriptionInstance + """ + payload, _, _ = await self._create_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + return TranscriptionInstance(self._version, payload) + + async def create_with_http_info_async( + self, + voice_v2_configuration_transcription_request: Union[ + VoiceV2ConfigurationTranscriptionRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :param voice_v2_configuration_transcription_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + voice_v2_configuration_transcription_request=voice_v2_configuration_transcription_request + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, id_or_unique_name: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param id_or_unique_name: + """ + return TranscriptionContext(self._version, id_or_unique_name=id_or_unique_name) + + def __call__(self, id_or_unique_name: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param id_or_unique_name: + """ + return TranscriptionContext(self._version, id_or_unique_name=id_or_unique_name) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.TranscriptionList>" diff --git a/twilio/rest/voice/v2/type.py b/twilio/rest/voice/v2/type.py new file mode 100644 index 0000000000..36106ff921 --- /dev/null +++ b/twilio/rest/voice/v2/type.py @@ -0,0 +1,683 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TypeInstance(InstanceResource): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + """ + :ivar message: Error message + :ivar code: Twilio error code + :ivar status: status code + :ivar more_info: More information about the error + :ivar id: Configuration Identifier + :ivar account_sid: Account sid + :ivar unique_name: The unique name + :ivar description: The description + :ivar date_created: + :ivar date_updated: + :ivar configuration: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + type: Optional[str] = None, + id_or_unique_name: Optional[str] = None, + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + self.code: Optional[int] = payload.get("code") + self.status: Optional[int] = payload.get("status") + self.more_info: Optional[str] = payload.get("more_info") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + + self._solution = { + "type": type or self.type, + "id_or_unique_name": id_or_unique_name or self.id_or_unique_name, + } + + self._context: Optional[TypeContext] = None + + @property + def _proxy(self) -> "TypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TypeContext for this TypeInstance + """ + if self._context is None: + self._context = TypeContext( + self._version, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TypeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TypeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TypeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TypeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "TypeInstance": + """ + Fetch the TypeInstance + + + :returns: The fetched TypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TypeInstance": + """ + Asynchronous coroutine to fetch the TypeInstance + + + :returns: The fetched TypeInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> "TypeInstance": + """ + Update the TypeInstance + + :param voice_v2_configuration_request: + + :returns: The updated TypeInstance + """ + return self._proxy.update( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + async def update_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> "TypeInstance": + """ + Asynchronous coroutine to update the TypeInstance + + :param voice_v2_configuration_request: + + :returns: The updated TypeInstance + """ + return await self._proxy.update_async( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + def update_with_http_info( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TypeInstance with HTTP info + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TypeInstance with HTTP info + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_v2_configuration_request=voice_v2_configuration_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.TypeInstance {}>".format(context) + + +class TypeContext(InstanceContext): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version, type: str, id_or_unique_name: str): + """ + Initialize the TypeContext + + :param version: Version that contains the resource + :param type: + :param id_or_unique_name: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + "id_or_unique_name": id_or_unique_name, + } + self._uri = "/Configurations/{type}/{id_or_unique_name}".format( + **self._solution + ) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TypeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TypeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TypeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TypeInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TypeInstance: + """ + Fetch the TypeInstance + + + :returns: The fetched TypeInstance + """ + payload, _, _ = self._fetch() + return TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TypeInstance: + """ + Asynchronous coroutine to fetch the TypeInstance + + + :returns: The fetched TypeInstance + """ + payload, _, _ = await self._fetch_async() + return TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TypeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> TypeInstance: + """ + Update the TypeInstance + + :param voice_v2_configuration_request: + + :returns: The updated TypeInstance + """ + payload, _, _ = self._update( + voice_v2_configuration_request=voice_v2_configuration_request + ) + return TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + def update_with_http_info( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TypeInstance and return response metadata + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + voice_v2_configuration_request=voice_v2_configuration_request + ) + instance = TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = voice_v2_configuration_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> TypeInstance: + """ + Asynchronous coroutine to update the TypeInstance + + :param voice_v2_configuration_request: + + :returns: The updated TypeInstance + """ + payload, _, _ = await self._update_async( + voice_v2_configuration_request=voice_v2_configuration_request + ) + return TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + + async def update_with_http_info_async( + self, + voice_v2_configuration_request: Union[ + VoiceV2ConfigurationRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TypeInstance and return response metadata + + :param voice_v2_configuration_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + voice_v2_configuration_request=voice_v2_configuration_request + ) + instance = TypeInstance( + self._version, + payload, + type=self._solution["type"], + id_or_unique_name=self._solution["id_or_unique_name"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V2.TypeContext {}>".format(context) + + +class TypeList(ListResource): + + class VoiceV2ConfigurationRequest(object): + """ + :ivar unique_name: The unique name + :ivar description: The description + :ivar configuration: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get( + "configuration" + ) + + def to_dict(self): + return { + "unique_name": self.unique_name, + "description": self.description, + "configuration": self.configuration, + } + + def __init__(self, version: Version): + """ + Initialize the TypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, type: str, id_or_unique_name: str) -> TypeContext: + """ + Constructs a TypeContext + + :param type: + :param id_or_unique_name: + """ + return TypeContext( + self._version, type=type, id_or_unique_name=id_or_unique_name + ) + + def __call__(self, type: str, id_or_unique_name: str) -> TypeContext: + """ + Constructs a TypeContext + + :param type: + :param id_or_unique_name: + """ + return TypeContext( + self._version, type=type, id_or_unique_name=id_or_unique_name + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V2.TypeList>" diff --git a/twilio/rest/voice/v3/__init__.py b/twilio/rest/voice/v3/__init__.py new file mode 100644 index 0000000000..9d9bd3733b --- /dev/null +++ b/twilio/rest/voice/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.voice.v3.transcription import TranscriptionList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Voice + + :param domain: The Twilio.voice domain + """ + super().__init__(domain, "v3") + self._transcriptions: Optional[TranscriptionList] = None + + @property + def transcriptions(self) -> TranscriptionList: + if self._transcriptions is None: + self._transcriptions = TranscriptionList(self) + return self._transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V3>" diff --git a/twilio/rest/voice/v3/transcription.py b/twilio/rest/voice/v3/transcription.py new file mode 100644 index 0000000000..5ade4ce6fe --- /dev/null +++ b/twilio/rest/voice/v3/transcription.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio API definition for public-api voice + Powers Twilio public-api voice + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TranscriptionInstance(InstanceResource): + """ + :ivar operation_id: Unique identifier for the transcription operation. + :ivar status: Current status of the transcription operation. PENDING: accepted but not yet started. RUNNING: currently in progress. COMPLETED: successfully completed. FAILED: failed and cannot be completed. + :ivar status_url: URL to poll for the latest operation status. + :ivar transcription: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + transcription_id: Optional[str] = None, + ): + super().__init__(version) + + self.operation_id: Optional[str] = payload.get("operationId") + self.status: Optional["TranscriptionInstance.str"] = payload.get("status") + self.status_url: Optional[str] = payload.get("statusUrl") + self.transcription: Optional[VoiceV3TranscriptionTranscription] = payload.get( + "transcription" + ) + + # Only set _solution if path params are provided (not None) + if transcription_id is not None: + self._solution = { + "transcription_id": transcription_id, + } + + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + transcription_id=self._solution["transcription_id"], + ) + return self._context + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V3.TranscriptionInstance {}>".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, transcription_id: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param transcription_id: The unique identifier of the transcription to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcription_id": transcription_id, + } + self._uri = "/Transcriptions/{transcription_id}".format(**self._solution) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + payload, _, _ = await self._fetch_async() + return TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = TranscriptionInstance( + self._version, + payload, + transcription_id=self._solution["transcription_id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V3.TranscriptionContext {}>".format(context) + + +class TranscriptionList(ListResource): + + class CreateV3TranscriptionsRequest(object): + """ + :ivar transcription_configuration_id: The ID of the transcription configuration to use + :ivar input_source: Discriminator indicating the input source type + :ivar source_id: The SID or TTID of the source audio to transcribe (e.g. a Twilio Recording SID). When provided, audioStartedAt is inferred from the recording's start time and does not need to be supplied by the caller. + :ivar participants: Participants in the conversation. If omitted or partially specified, defaults from the transcription configuration will be applied. + :ivar media_url: URL to the media file to transcribe + :ivar audio_started_at: The start time of the audio recording + """ + + def __init__(self, payload: Dict[str, Any]): + + self.transcription_configuration_id: Optional[str] = payload.get( + "transcriptionConfigurationId" + ) + self.input_source: Optional["TranscriptionInstance.str"] = payload.get( + "inputSource" + ) + self.source_id: Optional[str] = payload.get("sourceId") + self.participants: Optional[ + List[TranscriptionList.VoiceV3TranscriptionParticipant] + ] = payload.get("participants") + self.media_url: Optional[str] = payload.get("mediaUrl") + self.audio_started_at: Optional[datetime] = payload.get("audioStartedAt") + + def to_dict(self): + return { + "transcriptionConfigurationId": self.transcription_configuration_id, + "inputSource": self.input_source, + "sourceId": self.source_id, + "participants": ( + [participants.to_dict() for participants in self.participants] + if self.participants is not None + else None + ), + "mediaUrl": self.media_url, + "audioStartedAt": self.audio_started_at, + } + + class VoiceV3TranscriptionParticipant(object): + """ + :ivar type: The role of this participant in the conversation. + :ivar address: The phone number or identifier for this participant (E.164 format for phone numbers). Used to correlate this participant with their profile and conversation history. + :ivar name: User-defined name for this participant + :ivar audio_channel_index: One-based index of the audio channel in a multi-channel recording + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["TranscriptionInstance.str"] = payload.get("type") + self.address: Optional[str] = payload.get("address") + self.name: Optional[str] = payload.get("name") + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + + def to_dict(self): + return { + "type": self.type, + "address": self.address, + "name": self.name, + "audioChannelIndex": self.audio_channel_index, + } + + class VoiceV3TranscriptionResolvedConfiguration(object): + """ + :ivar transcription_engine: The engine used for transcription (Deepgram, Google, or auto) + :ivar speech_model: The speech model used for transcription (e.g., nova-2, nova-3, chirp_2) + :ivar language: The language code for transcription + :ivar transcription_status_callback: + :ivar conversation_configuration_id: Maestro conversation configuration ID + :ivar participant_defaults: Default participant configurations for the transcription + """ + + def __init__(self, payload: Dict[str, Any]): + + self.transcription_engine: Optional[str] = payload.get( + "transcriptionEngine" + ) + self.speech_model: Optional[str] = payload.get("speechModel") + self.language: Optional[str] = payload.get("language") + self.transcription_status_callback: Optional[ + VoiceV3TranscriptionTranscriptionStatusCallback + ] = payload.get("transcriptionStatusCallback") + self.conversation_configuration_id: Optional[str] = payload.get( + "conversationConfigurationId" + ) + self.participant_defaults: Optional[ + List[VoiceV3TranscriptionResolvedConfigurationParticipantDefaults] + ] = payload.get("participantDefaults") + + def to_dict(self): + return { + "transcriptionEngine": self.transcription_engine, + "speechModel": self.speech_model, + "language": self.language, + "transcriptionStatusCallback": ( + self.transcription_status_callback.to_dict() + if self.transcription_status_callback is not None + else None + ), + "conversationConfigurationId": self.conversation_configuration_id, + "participantDefaults": ( + [ + participant_defaults.to_dict() + for participant_defaults in self.participant_defaults + ] + if self.participant_defaults is not None + else None + ), + } + + class VoiceV3TranscriptionResolvedConfigurationParticipantDefaults(object): + """ + :ivar audio_channel_index: One-based index of the audio channel + :ivar type: The participant role type + """ + + def __init__(self, payload: Dict[str, Any]): + + self.audio_channel_index: Optional[int] = payload.get("audioChannelIndex") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "audioChannelIndex": self.audio_channel_index, + "type": self.type, + } + + class VoiceV3TranscriptionTranscriptionStatusCallback(object): + """ + :ivar url: The URL to call when transcription status changes + :ivar method: The HTTP method to use for the callback, currently only POST is supported + :ivar events: The transcription events that will trigger the callback + """ + + def __init__(self, payload: Dict[str, Any]): + + self.url: Optional[str] = payload.get("url") + self.method: Optional[str] = payload.get("method") + self.events: Optional[List[str]] = payload.get("events") + + def to_dict(self): + return { + "url": self.url, + "method": self.method, + "events": self.events, + } + + def __init__(self, version: Version): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Transcriptions" + + def _create( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_v3_transcriptions_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = self._create( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + return TranscriptionInstance(self._version, payload) + + def create_with_http_info( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptionInstance and return response metadata + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = create_v3_transcriptions_request.to_dict() + + headers = values.of( + { + "Idempotency-Key": idempotency_key, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: The created TranscriptionInstance + """ + payload, _, _ = await self._create_async( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + return TranscriptionInstance(self._version, payload) + + async def create_with_http_info_async( + self, + create_v3_transcriptions_request: CreateV3TranscriptionsRequest, + idempotency_key: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :param create_v3_transcriptions_request: + :param idempotency_key: A unique key to ensure idempotency. We recommend using UUID v7. Requests with the same key within the idempotency window return the original response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + create_v3_transcriptions_request=create_v3_transcriptions_request, + idempotency_key=idempotency_key, + ) + instance = TranscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, transcription_id: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param transcription_id: The unique identifier of the transcription to fetch + """ + return TranscriptionContext(self._version, transcription_id=transcription_id) + + def __call__(self, transcription_id: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param transcription_id: The unique identifier of the transcription to fetch + """ + return TranscriptionContext(self._version, transcription_id=transcription_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V3.TranscriptionList>" diff --git a/twilio/rest/wireless/v1/command.py b/twilio/rest/wireless/v1/command.py index a6e8f0b39d..caad0d64b8 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CommandContext] = None @property @@ -122,6 +124,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CommandInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CommandInstance": """ Fetch the CommandInstance @@ -140,6 +160,24 @@ async def fetch_async(self) -> "CommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -167,6 +205,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Commands/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CommandInstance @@ -174,10 +226,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CommandInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -186,55 +260,109 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> CommandInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the CommandInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched CommandInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + :returns: The fetched CommandInstance + """ + payload, _, _ = self._fetch() return CommandInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> CommandInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the CommandInstance + Fetch the CommandInstance and return response metadata - :returns: The fetched CommandInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + payload, _, _ = await self._fetch_async() return CommandInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -253,6 +381,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -277,7 +406,7 @@ def __init__(self, version: Version): self._uri = "/Commands" - def create( + def _create( self, command: str, sim: Union[str, object] = values.unset, @@ -286,19 +415,12 @@ def create( command_mode: Union["CommandInstance.CommandMode", object] = values.unset, include_sid: Union[str, object] = values.unset, delivery_receipt_requested: Union[bool, object] = values.unset, - ) -> CommandInstance: + ) -> tuple: """ - Create the CommandInstance - - :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. - :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. - :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. - :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. - :param command_mode: - :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. - :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + Internal helper for create operation - :returns: The created CommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -320,13 +442,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return CommandInstance(self._version, payload) - - async def create_async( + def create( self, command: str, sim: Union[str, object] = values.unset, @@ -337,7 +457,7 @@ async def create_async( delivery_receipt_requested: Union[bool, object] = values.unset, ) -> CommandInstance: """ - Asynchronously create the CommandInstance + Create the CommandInstance :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. @@ -349,6 +469,68 @@ async def create_async( :returns: The created CommandInstance """ + payload, _, _ = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -369,12 +551,79 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + payload, _, _ = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) return CommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -453,6 +702,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CommandInstance and returns headers from first page + + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CommandInstance and returns headers from first page + + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -480,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -518,6 +844,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -530,6 +857,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CommandInstance and returns headers from first page + + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CommandInstance and returns headers from first page + + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -620,6 +1021,100 @@ async def page_async( ) return CommandPage(self._version, response) + def page_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with CommandPage, status code, and headers + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = CommandPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> CommandPage: """ Retrieve a specific page of CommandInstance records from the API. diff --git a/twilio/rest/wireless/v1/rate_plan.py b/twilio/rest/wireless/v1/rate_plan.py index 458ade0ad5..77742cf2ba 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +24,11 @@ class RatePlanInstance(InstanceResource): + + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" + """ :ivar sid: The unique string that we created to identify the RatePlan resource. :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. @@ -79,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -114,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RatePlanInstance": """ Fetch the RatePlanInstance @@ -132,6 +157,24 @@ async def fetch_async(self) -> "RatePlanInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -168,6 +211,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -195,6 +274,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RatePlans/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RatePlanInstance @@ -202,10 +295,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -214,67 +329,119 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> RatePlanInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the RatePlanInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = self._fetch() return RatePlanInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> RatePlanInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the RatePlanInstance + Fetch the RatePlanInstance and return response metadata - :returns: The fetched RatePlanInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + payload, _, _ = await self._fetch_async() return RatePlanInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> RatePlanInstance: + ) -> tuple: """ - Update the RatePlanInstance + Internal helper for update operation - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. - - :returns: The updated RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -289,25 +456,58 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, ) -> RatePlanInstance: """ - Asynchronous coroutine to update the RatePlanInstance + Update the RatePlanInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. :returns: The updated RatePlanInstance """ + payload, _, _ = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -321,12 +521,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name + ) + instance = RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -345,6 +580,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -369,7 +605,7 @@ def __init__(self, version: Version): self._uri = "/RatePlans" - def create( + def _create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -382,23 +618,15 @@ def create( international_roaming: Union[List[str], object] = values.unset, national_roaming_data_limit: Union[int, object] = values.unset, international_roaming_data_limit: Union[int, object] = values.unset, - ) -> RatePlanInstance: + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> tuple: """ - Create the RatePlanInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. - :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. - :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. - :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). - :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). - :param voice_enabled: Deprecated. - :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). - :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. - :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. - :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. - - :returns: The created RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,6 +646,7 @@ def create( ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -426,13 +655,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return RatePlanInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -445,9 +672,12 @@ async def create_async( international_roaming: Union[List[str], object] = values.unset, national_roaming_data_limit: Union[int, object] = values.unset, international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, ) -> RatePlanInstance: """ - Asynchronously create the RatePlanInstance + Create the RatePlanInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. @@ -460,9 +690,101 @@ async def create_async( :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: :returns: The created RatePlanInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -481,6 +803,7 @@ async def create_async( ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) @@ -489,12 +812,113 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) return RatePlanInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RatePlanInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -545,6 +969,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -564,6 +1038,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -590,6 +1065,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -598,6 +1074,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RatePlanInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -664,6 +1190,76 @@ async def page_async( ) return RatePlanPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with RatePlanPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = RatePlanPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> RatePlanPage: """ Retrieve a specific page of RatePlanInstance records from the API. diff --git a/twilio/rest/wireless/v1/sim/__init__.py b/twilio/rest/wireless/v1/sim/__init__.py index cba0eeec71..33fee1d428 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -107,6 +108,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -142,6 +144,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SimInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SimInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SimInstance": """ Fetch the SimInstance @@ -160,6 +180,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -292,6 +330,138 @@ async def update_async( account_sid=account_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + @property def data_sessions(self) -> DataSessionList: """ @@ -336,6 +506,20 @@ def __init__(self, version: Version, sid: str): self._data_sessions: Optional[DataSessionList] = None self._usage_records: Optional[UsageRecordList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SimInstance @@ -343,10 +527,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SimInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({}) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) async def delete_async(self) -> bool: """ @@ -355,56 +561,110 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = await self._delete_async() + return success - headers = values.of({}) + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SimInstance and return response metadata - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - def fetch(self) -> SimInstance: + :returns: ApiResponse with success boolean, status code, and headers """ - Fetch the SimInstance + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation - :returns: The fetched SimInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + :returns: The fetched SimInstance + """ + payload, _, _ = self._fetch() return SimInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async(self) -> SimInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to fetch the SimInstance + Fetch the SimInstance and return response metadata - :returns: The fetched SimInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({}) headers["Accept"] = "application/json" - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers ) + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + payload, _, _ = await self._fetch_async() return SimInstance( self._version, payload, sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, unique_name: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -424,30 +684,12 @@ def update( voice_url: Union[str, object] = values.unset, reset_status: Union["SimInstance.ResetStatus", object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> SimInstance: + ) -> tuple: """ - Update the SimInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. - :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). - :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. - :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. - :param status: - :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. - :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. - :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. - :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. - :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. - :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). - :param voice_fallback_method: Deprecated. - :param voice_fallback_url: Deprecated. - :param voice_method: Deprecated. - :param voice_url: Deprecated. - :param reset_status: - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + Internal helper for update operation - :returns: The updated SimInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -478,13 +720,11 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return SimInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, unique_name: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -506,7 +746,7 @@ async def update_async( account_sid: Union[str, object] = values.unset, ) -> SimInstance: """ - Asynchronous coroutine to update the SimInstance + Update the SimInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. @@ -529,6 +769,123 @@ async def update_async( :returns: The updated SimInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -558,12 +915,145 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + payload, _, _ = await self._update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) return SimInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def data_sessions(self) -> DataSessionList: """ @@ -606,6 +1096,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -714,6 +1205,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["SimInstance.Status", object] = values.unset, @@ -743,6 +1316,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -784,6 +1358,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -797,6 +1372,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimInstance and returns headers from first page + + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["SimInstance.Status", object] = values.unset, @@ -893,6 +1548,106 @@ async def page_async( ) return SimPage(self._version, response) + def page_with_http_info( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with SimPage, status code, and headers + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = SimPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> SimPage: """ Retrieve a specific page of SimInstance records from the API. diff --git a/twilio/rest/wireless/v1/sim/data_session.py b/twilio/rest/wireless/v1/sim/data_session.py index b4c50d608d..cb0c14dc69 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: :param payload: Payload response from the API """ + return DataSessionInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -175,6 +177,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -194,6 +246,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -220,6 +273,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -228,6 +282,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -259,7 +363,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return DataSessionPage(self._version, response, self._solution) + return DataSessionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -292,7 +396,77 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return DataSessionPage(self._version, response, self._solution) + return DataSessionPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataSessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DataSessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DataSessionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DataSessionPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DataSessionPage: """ @@ -304,7 +478,7 @@ def get_page(self, target_url: str) -> DataSessionPage: :returns: Page of DataSessionInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DataSessionPage(self._version, response, self._solution) + return DataSessionPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> DataSessionPage: """ @@ -316,7 +490,7 @@ async def get_page_async(self, target_url: str) -> DataSessionPage: :returns: Page of DataSessionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DataSessionPage(self._version, response, self._solution) + return DataSessionPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/wireless/v1/sim/usage_record.py b/twilio/rest/wireless/v1/sim/usage_record.py index 1cd26b6c2e..5b1c6b2512 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -165,6 +167,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end: Union[datetime, object] = values.unset, @@ -190,6 +256,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -225,6 +292,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -236,6 +304,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end: Union[datetime, object] = values.unset, @@ -276,7 +412,7 @@ def page( response = self._version.page( method="GET", uri=self._uri, params=data, headers=headers ) - return UsageRecordPage(self._version, response, self._solution) + return UsageRecordPage(self._version, response, solution=self._solution) async def page_async( self, @@ -318,7 +454,95 @@ async def page_async( response = await self._version.page_async( method="GET", uri=self._uri, params=data, headers=headers ) - return UsageRecordPage(self._version, response, self._solution) + return UsageRecordPage(self._version, response, solution=self._solution) + + def page_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> UsageRecordPage: """ @@ -330,7 +554,7 @@ def get_page(self, target_url: str) -> UsageRecordPage: :returns: Page of UsageRecordInstance """ response = self._version.domain.twilio.request("GET", target_url) - return UsageRecordPage(self._version, response, self._solution) + return UsageRecordPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> UsageRecordPage: """ @@ -342,7 +566,7 @@ async def get_page_async(self, target_url: str) -> UsageRecordPage: :returns: Page of UsageRecordInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UsageRecordPage(self._version, response, self._solution) + return UsageRecordPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/wireless/v1/usage_record.py b/twilio/rest/wireless/v1/usage_record.py index 07135cf98b..034ab18ab2 100644 --- a/twilio/rest/wireless/v1/usage_record.py +++ b/twilio/rest/wireless/v1/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -152,6 +154,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end: Union[datetime, object] = values.unset, @@ -177,6 +243,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -212,6 +279,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +291,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end: Union[datetime, object] = values.unset, @@ -307,6 +443,94 @@ async def page_async( ) return UsageRecordPage(self._version, response) + def page_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with UsageRecordPage, status code, and headers + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = UsageRecordPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> UsageRecordPage: """ Retrieve a specific page of UsageRecordInstance records from the API. diff --git a/twilio/twiml/voice_response.py b/twilio/twiml/voice_response.py index 6f3d17e92c..8a5d0029bf 100644 --- a/twilio/twiml/voice_response.py +++ b/twilio/twiml/voice_response.py @@ -42,6 +42,7 @@ def dial( record=None, trim=None, recording_status_callback=None, + recording_configuration_id=None, recording_status_callback_method=None, recording_status_callback_event=None, answer_on_bridge=None, @@ -51,6 +52,7 @@ def dial( refer_url=None, refer_method=None, events=None, + passports=None, **kwargs ): """ @@ -66,6 +68,7 @@ def dial( :param record: Record the call :param trim: Trim the recording :param recording_status_callback: Recording status callback URL + :param recording_configuration_id: Configuration for the recording :param recording_status_callback_method: Recording status callback URL method :param recording_status_callback_event: Recording status callback events :param answer_on_bridge: Preserve the ringing behavior of the inbound call until the Dialed call picks up @@ -75,6 +78,7 @@ def dial( :param refer_url: Webhook that will receive future SIP REFER requests :param refer_method: The HTTP method to use for the refer Webhook :param events: Subscription to events + :param passports: Base64-encoded comma-separated identity passports (e.g. shaken, div) :param kwargs: additional attributes :returns: <Dial> element @@ -91,6 +95,7 @@ def dial( record=record, trim=trim, recording_status_callback=recording_status_callback, + recording_configuration_id=recording_configuration_id, recording_status_callback_method=recording_status_callback_method, recording_status_callback_event=recording_status_callback_event, answer_on_bridge=answer_on_bridge, @@ -100,6 +105,7 @@ def dial( refer_url=refer_url, refer_method=refer_method, events=events, + passports=passports, **kwargs ) ) @@ -313,6 +319,7 @@ def record( recording_status_callback_event=None, transcribe=None, transcribe_callback=None, + recording_configuration_id=None, **kwargs ): """ @@ -330,6 +337,7 @@ def record( :param recording_status_callback_event: Recording status callback events :param transcribe: Transcribe the recording :param transcribe_callback: Transcribe callback URL + :param recording_configuration_id: Configuration for the recording :param kwargs: additional attributes :returns: <Record> element @@ -348,6 +356,7 @@ def record( recording_status_callback_event=recording_status_callback_event, transcribe=transcribe, transcribe_callback=transcribe_callback, + recording_configuration_id=recording_configuration_id, **kwargs ) ) @@ -947,6 +956,52 @@ def transcription( ) ) + def recording( + self, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + trim=None, + track=None, + channels=None, + recording_configuration_id=None, + **kwargs + ): + """ + Create a <Recording> element + + :param recording_status_callback: Recording Status Callback URL + :param recording_status_callback_method: Recording Status Callback URL method + :param recording_status_callback_event: Recording Status Callback Events + :param trim: Trim the recording + :param track: To indicate which audio track should be recorded + :param channels: The recording channels for the final recording + :param recording_configuration_id: Configuration for the recording + :param kwargs: additional attributes + + :returns: <Recording> element + """ + return self.nest( + Recording( + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + track=track, + channels=channels, + recording_configuration_id=recording_configuration_id, + **kwargs + ) + ) + + +class Recording(TwiML): + """<Recording> TwiML Noun""" + + def __init__(self, **kwargs): + super(Recording, self).__init__(**kwargs) + self.name = "Recording" + class Prompt(TwiML): """<Prompt> Twiml Verb""" @@ -2178,6 +2233,7 @@ def conference( wait_method=None, max_participants=None, record=None, + recording_configuration_id=None, region=None, coach=None, trim=None, @@ -2204,6 +2260,7 @@ def conference( :param wait_method: Wait URL method :param max_participants: Maximum number of participants :param record: Record the conference + :param recording_configuration_id: Configuration for the recording :param region: Conference region :param coach: Call coach :param trim: Trim the conference recording @@ -2231,6 +2288,7 @@ def conference( wait_method=wait_method, max_participants=max_participants, record=record, + recording_configuration_id=recording_configuration_id, region=region, coach=coach, trim=trim, @@ -2354,7 +2412,7 @@ def sim(self, sim_sid, **kwargs): def sip( self, - sip_url, + sip_url=None, username=None, password=None, url=None, @@ -2395,7 +2453,7 @@ def sip( """ return self.nest( Sip( - sip_url, + sip_url=sip_url, username=username, password=password, url=url, @@ -2455,6 +2513,50 @@ def application( ) ) + def whats_app( + self, + phone_number, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <WhatsApp> element + + :param phone_number: WhatsApp Phone Number to dial + :param url: TwiML URL + :param method: TwiML URL Method + :param status_callback_event: Events to trigger status callback + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL Method + :param kwargs: additional attributes + + :returns: <WhatsApp> element + """ + return self.nest( + WhatsApp( + phone_number, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + +class WhatsApp(TwiML): + """<WhatsApp> TwiML Noun""" + + def __init__(self, phone_number, **kwargs): + super(WhatsApp, self).__init__(**kwargs) + self.name = "WhatsApp" + self.value = phone_number + class Application(TwiML): """<Application> TwiML Noun""" @@ -2501,10 +2603,93 @@ def __init__(self, sid, **kwargs): class Sip(TwiML): """<Sip> TwiML Noun""" - def __init__(self, sip_url, **kwargs): + def __init__(self, sip_url=None, **kwargs): super(Sip, self).__init__(**kwargs) self.name = "Sip" - self.value = sip_url + if sip_url: + self.value = sip_url + + def uri( + self, + sip_url=None, + priority=None, + weight=None, + username=None, + password=None, + **kwargs + ): + """ + Create a <Uri> element + + :param sip_url: The SIP URI + :param priority: The priority of this SIP URI + :param weight: The weight of this SIP URI + :param username: The username for authentication + :param password: The password for authentication + :param kwargs: additional attributes + + :returns: <Uri> element + """ + return self.nest( + SipUri( + sip_url=sip_url, + priority=priority, + weight=weight, + username=username, + password=password, + **kwargs + ) + ) + + def headers(self, **kwargs): + """ + Create a <Headers> element + + :param kwargs: additional attributes + + :returns: <Headers> element + """ + return self.nest(Headers(**kwargs)) + + +class Headers(TwiML): + """The SIP headers to include in the request""" + + def __init__(self, **kwargs): + super(Headers, self).__init__(**kwargs) + self.name = "Headers" + + def header(self, name=None, value=None, **kwargs): + """ + Create a <Header> element + + :param name: The name of the custom header + :param value: The value of the custom header + :param kwargs: additional attributes + + :returns: <Header> element + """ + return self.nest(Header(name=name, value=value, **kwargs)) + + +class Header(TwiML): + """A custom SIP header to include in the request""" + + def __init__(self, **kwargs): + super(Header, self).__init__(**kwargs) + self.name = "Header" + + +class SipUri(TwiML): + """The SIP URI to dial. Multiple Uri elements can be provided, in which + case they will be attempted in priority order. URIs with the same priority + will be selected proportionally based on its weight.""" + + def __init__(self, sip_url=None, **kwargs): + super(SipUri, self).__init__(**kwargs) + self.name = "Uri" + if sip_url: + self.value = sip_url class Sim(TwiML): @@ -2748,10 +2933,20 @@ def conversation_relay( dtmf_detection=None, welcome_greeting=None, partial_prompts=None, - interruptible=None, - interrupt_by_dtmf=None, welcome_greeting_interruptible=None, + interruptible=None, + preemptible=None, + hints=None, + intelligence_service=None, + report_input_during_agent_speech=None, + elevenlabs_text_normalization=None, + interrupt_sensitivity=None, debug=None, + backgroundNoiseReduction=None, + speechTimeout=None, + deepgramSmartFormat=None, + ignoreBackchannel=None, + events=None, **kwargs ): """ @@ -2769,10 +2964,20 @@ def conversation_relay( :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription :param welcome_greeting: The sentence to be played automatically when the session is connected :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking - :param interruptible: Whether caller's speaking can interrupt the play of text-to-speech - :param interrupt_by_dtmf: Whether DTMF tone can interrupt the play of text-to-speech - :param welcome_greeting_interruptible: Whether caller's speaking can interrupt the welcome greeting - :param debug: Whether debugging on the session is enabled + :param welcome_greeting_interruptible: "Whether and how the input from a caller, such as speaking or DTMF can interrupt the welcome greeting + :param interruptible: Whether and how the input from a caller, such as speaking or DTMF can interrupt the play of text-to-speech + :param preemptible: Whether subsequent text-to-speech or play media can interrupt the on-going play of text-to-speech or media + :param hints: Phrases to help better accuracy in speech recognition of these pharases + :param intelligence_service: The Conversational Intelligence Service id or unique name to be used for the session + :param report_input_during_agent_speech: Whether prompts should be reported to WebSocket server when text-to-speech playing and interrupt is disabled + :param elevenlabs_text_normalization: When using ElevenLabs as TTS provider, this parameter allows you to enable or disable its text normalization feature + :param interrupt_sensitivity: Set the sensitivity of the interrupt feature for speech. The value can be low, medium, or high + :param debug: Multiple debug options to be used for troubleshooting + :param backgroundNoiseReduction: This parameters enables background noise filtering on the audio stream before it reaches the STT engine, improving transcription accuracy in noisy environments + :param speechTimeout: Set the duration of silence that indicates the end of speech + :param deepgramSmartFormat: This parameter enables Deepgram's smart formatting feature, which automatically applies punctuation, capitalization, and formatting (e.g. numbers, dates, currency) to transcripts + :param ignoreBackchannel: This parameter brief caller acknowledgments (e.g. "yeah", "uh-huh") are ignored and will not interrupt the agent while it is speaking. + :param events: This parameter allows you to enable event subscriptions :param kwargs: additional attributes :returns: <ConversationRelay> element @@ -2791,138 +2996,77 @@ def conversation_relay( dtmf_detection=dtmf_detection, welcome_greeting=welcome_greeting, partial_prompts=partial_prompts, - interruptible=interruptible, - interrupt_by_dtmf=interrupt_by_dtmf, welcome_greeting_interruptible=welcome_greeting_interruptible, + interruptible=interruptible, + preemptible=preemptible, + hints=hints, + intelligence_service=intelligence_service, + report_input_during_agent_speech=report_input_during_agent_speech, + elevenlabs_text_normalization=elevenlabs_text_normalization, + interrupt_sensitivity=interrupt_sensitivity, debug=debug, + backgroundNoiseReduction=backgroundNoiseReduction, + speechTimeout=speechTimeout, + deepgramSmartFormat=deepgramSmartFormat, + ignoreBackchannel=ignoreBackchannel, + events=events, **kwargs ) ) - def assistant( - self, - id=None, - language=None, - tts_language=None, - transcription_language=None, - tts_provider=None, - voice=None, - transcription_provider=None, - speech_model=None, - profanity_filter=None, - dtmf_detection=None, - welcome_greeting=None, - partial_prompts=None, - interruptible=None, - interrupt_by_dtmf=None, - welcome_greeting_interruptible=None, - debug=None, - **kwargs - ): + def ai_session(self, ai_connector=None, ai_session_configuration=None, **kwargs): """ - Create a <Assistant> element + Create a <AiSession> element - :param id: The assistant ID of the AI Assistant - :param language: Language to be used for both text-to-speech and transcription - :param tts_language: Language to be used for text-to-speech - :param transcription_language: Language to be used for transcription - :param tts_provider: Provider to be used for text-to-speech - :param voice: Voice to be used for text-to-speech - :param transcription_provider: Provider to be used for transcription - :param speech_model: Speech model to be used for transcription - :param profanity_filter: Whether profanities should be filtered out of the speech transcription - :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription - :param welcome_greeting: The sentence to be played automatically when the session is connected - :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking - :param interruptible: Whether caller's speaking can interrupt the play of text-to-speech - :param interrupt_by_dtmf: Whether DTMF tone can interrupt the play of text-to-speech - :param welcome_greeting_interruptible: Whether caller's speaking can interrupt the welcome greeting - :param debug: Whether debugging on the session is enabled + :param ai_connector: The unique name or installed add-on sid that identifies the installed addon resource for the AI Connector + :param ai_session_configuration: The unique name or id of the AiSession Configuration resource. :param kwargs: additional attributes - :returns: <Assistant> element + :returns: <AiSession> element """ return self.nest( - Assistant( - id=id, - language=language, - tts_language=tts_language, - transcription_language=transcription_language, - tts_provider=tts_provider, - voice=voice, - transcription_provider=transcription_provider, - speech_model=speech_model, - profanity_filter=profanity_filter, - dtmf_detection=dtmf_detection, - welcome_greeting=welcome_greeting, - partial_prompts=partial_prompts, - interruptible=interruptible, - interrupt_by_dtmf=interrupt_by_dtmf, - welcome_greeting_interruptible=welcome_greeting_interruptible, - debug=debug, + AiSession( + ai_connector=ai_connector, + ai_session_configuration=ai_session_configuration, **kwargs ) ) - -class Assistant(TwiML): - """<Assistant> TwiML Noun""" - - def __init__(self, **kwargs): - super(Assistant, self).__init__(**kwargs) - self.name = "Assistant" - - def language( - self, - code=None, - tts_provider=None, - voice=None, - transcription_provider=None, - speech_model=None, - **kwargs + def conversation_relay_session( + self, connector=None, session_configuration=None, **kwargs ): """ - Create a <Language> element + Create a <ConversationRelaySession> element - :param code: Language code of this language setting is for - :param tts_provider: Provider to be used for text-to-speech of this language - :param voice: Voice to be used for text-to-speech of this language - :param transcription_provider: Provider to be used for transcription of this language - :param speech_model: Speech model to be used for transcription of this language + :param connector: The unique name or installed add-on sid that identifies the installed addon resource for the ConversationRelaySession Connector + :param session_configuration: The unique name or id of the ConversationRelaySession Configuration resource. :param kwargs: additional attributes - :returns: <Language> element + :returns: <ConversationRelaySession> element """ return self.nest( - Language( - code=code, - tts_provider=tts_provider, - voice=voice, - transcription_provider=transcription_provider, - speech_model=speech_model, + ConversationRelaySession( + connector=connector, + session_configuration=session_configuration, **kwargs ) ) - def parameter(self, name=None, value=None, **kwargs): - """ - Create a <Parameter> element - :param name: The name of the custom parameter - :param value: The value of the custom parameter - :param kwargs: additional attributes +class ConversationRelaySession(TwiML): + """<ConversationRelaySession> TwiML Noun""" - :returns: <Parameter> element - """ - return self.nest(Parameter(name=name, value=value, **kwargs)) + def __init__(self, **kwargs): + super(ConversationRelaySession, self).__init__(**kwargs) + self.name = "ConversationRelaySession" -class Language(TwiML): - """<Language> TwiML Noun""" +class AiSession(TwiML): + """<AiSession> TwiML Noun""" def __init__(self, **kwargs): - super(Language, self).__init__(**kwargs) - self.name = "Language" + super(AiSession, self).__init__(**kwargs) + self.name = "AiSession" class ConversationRelay(TwiML): @@ -2977,6 +3121,14 @@ def parameter(self, name=None, value=None, **kwargs): return self.nest(Parameter(name=name, value=value, **kwargs)) +class Language(TwiML): + """<Language> TwiML Noun""" + + def __init__(self, **kwargs): + super(Language, self).__init__(**kwargs) + self.name = "Language" + + class Conversation(TwiML): """<Conversation> TwiML Noun"""